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