【问题标题】:How do I return a struct (from a function) containing an array with the correct elements in that array?如何返回一个结构(来自函数),其中包含一个数组,该数组中包含正确的元素?
【发布时间】:2016-10-04 01:55:05
【问题描述】:

我正在编写一个程序,它返回一个包含数组的结构,但数组中的元素完全错误。我一直在这个网站、谷歌、甚至 Bing 上寻找答案,但什么也没有。我能找到的最好的答案是这样的:

函数不能在 C 中返回数组。
但是,它们可以返回结构。而且结构可以包含数组...

来自How to make an array return type from C function?

现在,如何在不使用指针的情况下解决这个问题?

#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

【问题讨论】:

  • 请解释c.a[c.as];
  • 要完成这项工作,您需要在结构声明中指定数组大小,它不能根据运行时参数而变化
  • @MM 感谢您的帮助

标签: c arrays struct


【解决方案1】:

具有灵活值的structs 不是通过值来操作的,只能通过指针来操作。

您不能通过值返回具有灵活成员的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;

改变你的函数以返回一个指针;确保调用者释放结果。

【讨论】:

  • 经过测试,效果很好,感谢您编写代码,帮助我更好地理解它
【解决方案2】:

在你的函数struct Codes create(int as)中,struct Codes c;被分配在卡住了,所以一旦函数返回内存就不再有效...

...确实在返回值中复制了核心结构...但是可变数组长度c.a不是结构的一部分(它是内存“预告片”或“页脚”)和不会与返回值一起复制。

要么:

  1. 分配结构并将其传递给struct Codes create(struct Codes *dest, int as) 函数;或者

  2. 使结构数组的大小固定struct Codes{ int as; int a[4]; };

祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2011-02-02
    • 2019-11-06
    • 2018-04-20
    • 1970-01-01
    • 2016-04-27
    • 2017-02-06
    相关资源
    最近更新 更多