如何正确将包含整数数组的结构体分配给结构体数组?

3

我希望知道如何将包含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 

1
学习如何使用调试器并能够通过检查程序运行时变量的值来自己找到这些问题是很有必要的。 - M.M
抱歉,我不知道我怎么搞砸了,感谢你的帮助。 - Ray Burns
1个回答

1
"

struct Code *c = malloc(sizeof(struct Code*) + as * sizeof(struct Codes*)); 是不正确的。结构体 Code 的 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可以诊断此错误。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接