c - 如何正确地将包含 int 数组的结构分配给结构数组?

标签 c arrays struct flexible-array-member

我想知道如何将包含 int 数组的结构分配给结构数组。无论我想到什么新的解决方案,我总是得到不正确的结果。

我认为问题在于这段代码:

struct Codes *create(int as) {
    struct Codes *c = malloc(sizeof (struct Codes)+as * sizeof (int));
    c->as = as;
    for (int i = 0; i < as; i++) {
        c->a[i] = i;
    }

    return c;
}

完整代码:

#include <stdio.h>
#include <stdlib.h>  
#include <ctype.h>

struct Codes {
    int as;
    int a[];
};

struct Code {
    int as;
    struct Codes *ci[];
};

struct Codes *create(int as) {
    struct Codes *c = malloc(sizeof (struct Codes)+as * sizeof (int));
    c->as = as;
    for (int i = 0; i < as; i++) {
        c->a[i] = i;
    }

    return c;
}

struct Code *and(int as, struct Codes *cd) {
    struct Code *c = malloc(sizeof (struct Code)+as * sizeof (struct Codes));
     for (int i = 0; i < as; i++) {
        c->ci[i] = cd;
    }
    c->as = as;
    return c;
}

int main(int argc, char **argv) {

    struct Codes *cd;
    cd = create(4);

    struct Code *c;
    c = and(2, cd);

    for (int i = 0; i < c->as; i += 1) {
        for (int j=0; j < c->ci[i]->as; j++) {
            printf("%d \n", c->ci[i]->a[j]);
       }
    }

    free(cd);
    free(c);

}//main

实际结果:

0 
1 
2 
3 

预期结果:

0 
1 
2 
3
0
1
2
3 

最佳答案

struct Code *c = malloc(sizeof (struct Code)+as * sizeof (struct Codes));是不正确的。结构代码的 ci 是一个指针数组,但您为结构数组分配了空间。

要解决此问题,请更改为 sizeof(struct Codes *) ,或者最好使用取消引用指向您为其分配空间的类型的指针的模式:

struct Code *c = malloc( sizeof *c + as * sizeof c->ci[0] );

此外,for (int j;应该是 for (int j = 0; .您的代码使用 j 的未初始化值导致未定义的行为,这只是你碰巧得到你所做的输出的机会。使用 gcc 标志 -Wextra会诊断出这个错误。

关于c - 如何正确地将包含 int 数组的结构分配给结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39864902/

相关文章:

c - 理解 C 中的增量运算符

c++ - 计算数字的总和乘以字符串的长度

c - 获取数组的两个地址的差异(使用 & 运算符)

javascript - 为什么在这个 JavaScript 示例中移位比索引访问更快?

java - 力扣 : Partition array according to a pivot

c - 结构之前的预期表达式错误

c - 为什么输出会趋于无穷大

c# - 为什么类数组消耗的内存比结构数组多 20%?

c - getchar() 用于从输入中排除字符

c - C 中的结构体和函数