c - 初始化数组中结构体中的变量

标签 c

我创建了结构数组,并在函数 config_course_list 中使用包含类(class)信息的文件创建了它们。 我测试了函数的变量,它是正确的。但是,当我在 main 中调用此函数时,*courses 的大小为 1,仅包含一个结构。我可以打印 courses[0].codecourses[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].codecourselist_ptr[index]->description by (*courselist_ptr)[index].description.

关于c - 初始化数组中结构体中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52771764/

相关文章:

c - 汇编中没有换行符的 Printf

无法理解为什么 c 中的 malloc 函数会如下所述执行操作?

在 OS X 上编译 C 程序以在 Linux 上运行

C char* 与 URL 内容

c - 在 C 中分配二维数组

c - 引用超出结构大小的 malloc 字节

c - 从内核到用户空间(DMA)

iphone - 使用 C 或 Objective-C 加密不同类型的文件

c - 如何检查 struct timer_list 是否过期?

C - 如何将 select() 与多个管道一起使用?