c - 从文件读取时出现分段错误
问题描述
我正在处理结构和字符指针(字符串)。我想制作一个结构数组,这些结构有一个char*
, 和两个int
s。
fscanf
尝试进入array
and struct
s时出现分段错误。
这是我的代码的相关部分。
结构定义
typedef struct {
char* title;
int gross;
int year;
} Movie;
我遇到问题的功能
Movie* createArray(char *filename, int size)
{
FILE *f;
f = fopen(filename, "r");
Movie* arr = (Movie*) malloc(sizeof(Movie) * size);
if(!arr){printf("\nAllocation Failed\n"); exit(1);}
for (int i =0; i<size; i++){
fscanf(f, "%s %d %d", (arr+ i)->title, &arr[i].gross, &arr[i].year);
}
fclose(f);
return arr;
}
添加到它以防万一这里是我调用该函数的方式
Movie* arr = createArray(file1, records);
解决方案
title
是一个未初始化的指针,您还需要为其保留内存,或者如果可以选择,则只需声明title
为char array
具有所需大小的 a 。
还有一些我想在你的函数中解决的其他问题,其中一些你可能知道,下面的代码带有注释。
Movie* createArray(char *filename, int size)
{
FILE *f;
if(!(f = fopen(filename, "r"))){ //also check for file opening
perror("File not found");
exit(EXIT_FAILURE); //or return NULL and handle it on the caller
}
//don't cast malloc, #include <stdlib.h>, using the dereferenced pointer in sizeof
//is a trick commonly used to avoid future problems if the type needs to be changed
Movie* arr = malloc(sizeof(*arr) * size);
if(!arr) {
perror("Allocation Failed"); //perror is used to output the error signature
exit(EXIT_FAILURE);
}
for (int i =0; i<size; i++) {
if(!((arr + i)->title = malloc(100))){ // 99 chars plus null terminator,
perror("Allocation failed"); // needs to be freed before the array
exit(EXIT_FAILURE); //using EXIT_FAILURE macro is more portable
}
//always check fscanf return, and use %99s specifier
//for 100 chars container to avoid overflow
if(fscanf(f, "%99s %d %d", (arr+ i)->title, &arr[i].gross, &arr[i].year) != 3){
exit(EXIT_FAILURE); //or return NULL and handle it on the caller
}
}
fclose(f);
return arr;
}
推荐阅读
- django - django 服务器不显示也不停止
- python - 使用多个窗口过滤 PySpark 数据帧的行
- vba - 使用 Comment 记录单元格中的每一个变化
- django - Django - 有没有更好的方法从表单字段中获取数据?
- excel - 如何使用 Excel VBA 中的 Join 函数克服类型不匹配错误
- android - 由于 GRPC 和 R8,Firestore (0.6.6-dev) 出现内部错误
- javascript - NextJS:getInitialProps 方法
- java - 如何检查mysql与eclipse的兼容性
- angular - Angular 服务不适用于 http.get observable
- pandas - 获取熊猫数据框的多列(笛卡尔积)的组合?