【发布时间】:2010-09-22 05:15:35
【问题描述】:
我正在尝试编写一个程序,该程序使用输入重定向将文件中的条目读入动态分配的结构数组中。我的程序编译得很好,但我遇到了分段错误,我很难找到原因。
这是我的程序:
#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 比较陌生!
【问题讨论】:
标签: c arrays segmentation-fault structure