【发布时间】: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 感谢您的帮助