[英]How do I return a struct (from a function) containing an array with the correct elements in that array?
我正在编写一个返回包含数组的结构的程序,但是数组中的元素完全错误。 我一直在这个网站,Google甚至Bing上搜索答案,但一无所获。 我能找到的最好的答案是这样的:
函数无法在C中返回数组。
但是,它们可以返回结构。 结构可以包含数组...
现在,如何在不使用指针的情况下解决此问题?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
struct Codes{
int as;
int a[];
};
struct Codes create(int as){
int a[as];
for(int j = 0;j<as;j++)
a[j]=j+1;
struct Codes c;
c.as = as;
c.a[c.as];
for(int i=0; i<as; i++)
c.a[i] = a[i];
for(int i=0; i<as; i+=1)
printf("%d \n", c.a[i]);
return c;
}
int main(int argc, char **argv) {
struct Codes cd;
int as = 4;
cd = create(as);
for(int i=0; i<4; i+=1)
printf("%d \n", cd.a[i]);
}
实际输出:
1
2
3
4
0
0
2
-13120
预期产量:
1
2
3
4
1
2
3
4
在您的函数中, struct Codes create(int as)
, struct Codes c;
分配在卡住的内存上,因此一旦函数返回,内存将不再有效...
...确实是将核心结构复制到返回值中...但是可变数组长度ca
不是该结构的一部分(它是内存“ trailer”或“ footer”),并且不会一起复制与返回值。
或者:
分配结构并将其传递给struct Codes create(struct Codes *dest, int as)
函数; 要么
使结构数组的大小固定在struct Codes{ int as; int a[4]; };
struct Codes{ int as; int a[4]; };
祝好运。
具有灵活值的struct
并不意味着只能通过指针来操作值。
您不能通过值返回带有弹性成员的struct
,因为C不知道需要为返回值分配多少项,以及需要复制多少字节。
使用足够大小的malloc
在动态内存中分配struct
,将数据复制到其中,并返回指向调用方的指针:
struct Codes *c = malloc(sizeof(struct Codes)+as*sizeof(int));
c->as = as;
for (int i = 0 ; i != as ; i++) {
c->a[i] = i+1;
}
return c;
更改函数以返回指针; 确保调用者释放结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.