gpt4 book ai didi

c - C 中的动态结构和指针

转载 作者:行者123 更新时间:2023-11-30 19:18:28 24 4
gpt4 key购买 nike

我的 C 程序遇到一些问题。函数 create_class_list应该从输入文件中读取学生的 ID,动态分配存储学生列表所需的内存并初始化学生的 ID。

更具体地说:

  • 分配一个指向 student 的指针数组.
  • student 类型的每个变量分配内存.
  • 将成员初始化为正确的 ID 值。
  • 将数组中的每个指针设置为指向 student 类型的变量.
  • 返回指向 student 的指针数组开头的指针。

这是我到目前为止的代码:

我的结构学生:

typedef struct{

int ID;
int project_grade;
int exam_grade;
float course_mark;
struct student *student;

}student;

我的类(class)列表功能:

student **create_class_list( char *filename, int *sizePtr )
{
int i = 0;
student **StructPtr;
student *students;

FILE *input_file = fopen("IDnumbers.txt", "r"); //opens input file for reading
fscanf(input_file,"%d", sizePtr ); //scans the number of students from input file

StructPtr = (student**)calloc(*sizePtr, sizeof(student*)); // creates an array of pointers to student
student **original = StructPtr; // makes a pointer to the first element
students = (student*)calloc(*sizePtr, sizeof(student)); // creates an array of type student of 'x' students

while(i < *sizePtr){

StructPtr[i] = &students[i];
fscanf(input_file,"%d",students[i].ID ); //allocates IDs to all students
students[i].course_mark = 0; //initializes all grades to 0
students[i].exam_grade = 0; //initializes all grades to 0
students[i].project_grade = 0; // initializes all grades to 0
i++; // increments counter
}

fclose(input_file); //closes file
return original; //returns pointer to first element
}

我的主要测试功能:

int main()
{
int NumberStudents = 0; // number of students in class
int i; //counter variable
student **x;

x = create_class_list("IDnumbers.txt", &NumberStudents);

printf("%d\n",(**x).ID);
return 0;
}

输出应该是输入文件中的第一个学生#。程序编译,但崩溃了:/有什么建议吗?

最佳答案

您需要更改一行。

fscanf(input_file,"%d", &students[i].ID);

因为 fscanf 的参数是指针。

关于c - C 中的动态结构和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26704568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com