我正在处理文件,这在编译后给了我一个段错误错误。 我正在尝试打开一个文件并将其保存在 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/