[英]How do I correctly assign a struct containing an array of int to an array of struct?
我想知道如何將包含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));
是不正確的。 struct Code的ci是一個指針數組,但是你為一個結構數組分配了空間。
要解決此問題,請更改為sizeof(struct Codes *)
,或者最好使用解除引用指向您為其分配空間的類型的指針的模式:
struct Code *c = malloc( sizeof *c + as * sizeof c->ci[0] );
另外, for (int j;
應該是for (int j = 0;
-Wextra
你的代碼通過使用未初始化的j
值導致未定義的行為,這恰好是你碰巧得到你輸出的結果。使用gcc標志-Wextra
會有診斷出這個錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.