C 程序。文件。

标签 c file segmentation-fault

我正在处理文件,这在编译后给了我一个段错误错误。 我正在尝试打开一个文件并将其保存在 vector 中。我还想使用动态内存来分配它。

 #include "stdio.h"
#include "stdlib.h"

main(){

  int n,v[n],i,c,cant;


  FILE*archivo;

  archivo = fopen("vectores.dat","wb");
    if(archivo == NULL)
    {
      printf("Error while opening");
      exit(1);
    }


  printf("write the number of integers you want to save in the file");
  scanf("%d",&cant);


  for(i=0;i<cant;i++){

    printf("write the number in the position:  %d",i+1);
    scanf("%d",v[i]);
  }


  c= fwrite(v,sizeof(int),n,archivo);
    if(c<1){

    printf("Error while writing");
    exit(1);
    }

}

最佳答案

这是一个问题:

int n,v[n],...

首先声明变量n,但不初始化它,然后将v声明为n整数数组。问题在于,由于 n 未初始化,因此其值是不确定,并且您有 undefined behavior .

您稍后再次使用n,但仍然没有初始化。

如果您的程序在任何地方都有未定义的行为,则它的格式不正确,并且任何代码都不可信。

关于C 程序。文件。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26073034/

相关文章:

c++ - 删除指针的段错误

c++ - 如何从不同的函数而不是 main() 开始执行 c/c++ 中的程序

c - 通过链表输入字符串

c - 为什么 fgetc 太慢了?

c - 用C读取文件

ios - 从框架导入所有文件?

linux - 什么Linux类相当于CStdioFile

c - 为什么这段代码会导致段错误错误?

c - 标准输入上最受欢迎的字符

linux - SECTION .DATA 中变量的段错误