简体   繁体   English

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

[英]How do I correctly assign a struct containing an array of int to an array of struct?

I want to know how to assign a struct containing an array of int to an array of structs. 我想知道如何将包含int数组的结构分配给结构数组。 I keep getting the incorrect result no matter what new solution I think of. 无论我想到什么新的解决方案,我都会得到错误的结果。

I believe the problem lies in this piece of code: 我相信问题在于这段代码:

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;
}

The whole code: 整个代码:

#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

Actual Result: 实际结果:

0 
1 
2 
3 

Expected Result: 预期结果:

0 
1 
2 
3
0
1
2
3 

struct Code *c = malloc(sizeof (struct Code)+as * sizeof (struct Codes)); is incorrect. 是不正确的。 The struct Code 's ci is an array of pointers , but you allocated space for an array of structs. struct Code的ci是一个指针数组,但是你为一个结构数组分配了空间。

To fix this, either change to sizeof(struct Codes *) , or preferably use the pattern of dereferencing the pointer to the type you're allocating space for: 要解决此问题,请更改为sizeof(struct Codes *) ,或者最好使用解除引用指向您为其分配空间的类型的指针的模式:

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

Also, for (int j; should be for (int j = 0; . Your code causes undefined behaviour by using uninitialized value of j , it's just chance that you happened to get the output you did. Using the gcc flag -Wextra would have diagnosed this error. 另外, for (int j;应该是for (int j = 0; -Wextra你的代码通过使用未初始化的j值导致未定义的行为,这恰好是你碰巧得到你输出的结果。使用gcc标志-Wextra会有诊断出这个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM