我创建了结构数组,并在函数a = np.concatenate((X, Y, Z))
print(a)
[ 1 2 3 4 5 6 7 8 9 10 11 12]
中使用包含课程信息的文件创建了它们。
我在函数的处测试了变量,它是正确的。但是,当我在config_course_list
中调用此函数时,main
的大小为1,仅包含一个结构。我可以打印*courses
和courses[0].code
,但不能打印courses[0].description
和courses[1].code
。
我应该怎么做才能使其正常工作?
config_course_list:
description
主要:
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);
答案 0 :(得分:2)
删除这些行:
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
的{{1}}和(*courselist_ptr)[index].code
的{{1}}。