我创建了结构数组,并在函数 config_course_list
中使用包含类(class)信息的文件创建了它们。
我测试了函数的变量,它是正确的。但是,当我在 main
中调用此函数时,*courses
的大小为 1,仅包含一个结构。我可以打印 courses[0].code
和 courses[0].description
,但无法打印 courses[1].code
和描述
。
我应该怎么做才能让它发挥作用?
配置类(class)列表:
int config_course_list(Course **courselist_ptr, char *config_filename) {
FILE *f;
char buff[INPUT_BUFFER_SIZE];
f = fopen(config_filename, "r");
if (f == NULL)
{
perror("file");
}
fgets(buff,INPUT_BUFFER_SIZE+1,f);
int size = atoi(buff);
*courselist_ptr = (Course *)malloc(size * sizeof(Course));
for (int i = 0; i < size; ++i)
{
courselist_ptr[i] = malloc(sizeof(Course));
}
int index = 0;
char *token[size];
for (int i = 0; i < size; ++i)
{
token[i] = malloc(sizeof(char)*INPUT_BUFFER_SIZE);
}
while (fgets(buff,INPUT_BUFFER_SIZE+1, f) != NULL)
{
strcpy(courselist_ptr[index]->code, strtok(buff, " "));
strcpy(token[index],strtok(NULL, "\n"));
courselist_ptr[index]->description=token[index];
index ++;
}
return size;
}
主要:
Course *courses;
int num_courses = config_course_list(&courses, argv[1]);
printf("%s\n", courses[1].code);
类(class)结构:
struct course{
char code[7];
char *description;
};
最佳答案
删除这些行:
for (int i = 0; i < size; ++i)
{
courselist_ptr[i] = malloc(sizeof(Course));
}
上面循环的目的是什么?看起来您想创建 2D 数组...而不是这样。
您的目标是创建一维数组,您可以通过以下方式实现
*courselist_ptr = (Course *)malloc(size * sizeof(Course));
这就足够了,现在数组已经创建了,你可以用一些数据填充它。
当您创建一维数组时,
和 p
指向该数组的第一个元素,您有两种方法
访问第 i 个元素:
p[i]
或
*(p + i)
^ - p is pointer to first element of array
在你的情况下p
是*courselist_ptr
因此,如果您想读/写 code
成员,您可以使用:
(*courselist_ptr)[i].code
(*courselist_ptr + i)->code
(*(*courselist_ptr + i)).code
所以你必须更换
courselist_ptr[index]->code
by (*courselist_ptr)[index].code
和 courselist_ptr[index]->description
by (*courselist_ptr)[index].description
.
关于c - 初始化数组中结构体中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52771764/