1

I've read and looked at some example of flexible array members but I am not exactly sure how to add and read elements of this variable length array.

typedef struct School {
    char *name;
    char *courses[]; //Flexible Array Member
} School;

1) Can someone please show me an example of how I can add an element to this Flexible Length Member and print it after it is stored.

2) I also would like to know how to malloc it correctly. Based on what I have read about Flexible Array Members, we would need to add more space for the flexible array member and can't just use sizeof(School);. My only issue is how do I know how much do add for that flexible member.

4

3 回答 3

1

您应该修改struct以添加分配结构中存在的课程数量:

typedef struct School {
    char *name;
    int ncourses;
    char *courses[]; //Flexible Array Member
} School;

假设你有 2 所学校,一所有 3 门课程,一所有 2 门课程。你可以这样分配结构:

School *mc = malloc(offsetof(struct School, courses) + 3 * sizeof(char *));
mc->name = strdup("Math College");
mc->ncourses = 3;
mc->courses[0] = strdup("Math 101");
mc->courses[1] = strdup("Math 102");
mc->courses[2] = strdup("Math 103");

School *ps = malloc(offsetof(struct School, courses) + 2 * sizeof(char *));
ps->name = strdup("Psycho School");
ps->ncourses = 2;
ps->courses[0] = strdup("Psycho 101");
ps->courses[1] = strdup("Unknown 404");

如您所见,变量数组的元素像任何其他数组元素一样被访问。该调用为位于结构末尾的malloc结构成员和数组元素(此处为指针)分配适当的字节大小。char *

您可以使用通用函数来分配和初始化此类结构:

School create_school(const char *school_name, int ncourses, char *courses[]) {
    School *sp = malloc(offsetof(struct School, courses) + ncourses * sizeof(char *));
    sp->name = strdup(school_name);
    sp->ncourses = ncourses;
    for (int i = 0; i < ncourses; i++) {
        sp->courses[i] = strdup(courses[i]);
    }
    return sp;
}
于 2016-01-24T01:30:07.257 回答
0

本质上,该技术是为结构动态分配足够的内存,加上最后一个数组的元素。

School *data = malloc(sizeof(*data) + number * sizeof(*(data->courses)));

for (i = 0; i < number; ++i)
{
     const char hello[] = "Hello";
     data->courses[i] = malloc(strlen(hello) + 1));   /* sizeof char is 1 by definition */
     strcpy(courses[i], hello);
}
于 2016-01-24T01:30:23.910 回答
0

计算结构所需尺寸的确切公式是:

size_t need = offsetof(struct School, courses) + num_courses * sizeof(char *);

注意使用offsetof. 有些人使用sizeof,但这会由于结构填充而引入内存开销。

于 2016-01-24T00:40:59.563 回答