我正在尝试编写一个程序,该程序使用输入重定向将文件中的条目读入到动态分配的结构数组中。我的程序编译正常,但我遇到了段错误,而且我无法找到原因。
这是我的程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct StudentData
{
char* name;
char* major;
double gpa;
} Student;
int main()
{
Student* data = (Student*)malloc(sizeof(Student)*5);
int i;
for(i = 0; i < 5; i++)
{
// allocate memory for name and read input
data[i].name = malloc(50);
*(data+i)->name == scanf("%s", (char*)&data[i].name);
// allocate memory for major and read input
data[i].major = malloc(30);
*(data+i)->major == scanf("%s", (char*)&data[i].major);
// read input for gpa
(data+i)->gpa == scanf("%lf", &data[i].gpa);
//print array
printf("%s\n%s\n%f\n", data[i].name, data[i].major, data[i].gpa);
}
}
有什么线索吗?如果它看起来很明显,那是因为我对 C 比较陌生!
最佳答案
这一行:
*(data+i)->name == scanf("%s", (char*)&data[i].name);
暂时忽略奇怪和无效的 ==
, &data[i].name
是错误的,因为您正在获取指针的地址。 data[i].name
在这里就足够了,因为 name
字段已经是 scanf
可以写入的地址。
(char*)
的强制转换可能关闭编译器 - 你输入它是为了这个目的吗:-)?因为 &data[i].name
的类型是 char**
,scanf
不会接受,除非你强行将它转换为 char*
.
作为一般建议,尽量避免使用 scanf
- 它会导致非常不安全的代码(正如您刚刚看到的!)相反,请使用 fgets
来读取一行(也来自标准输入)然后将这条线分解成它的组成部分。这最初可能需要更多的代码来实现,但会导致更安全和更可预测的代码。
关于c - 我的段错误的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3766506/