我正在做一個程序,返回一個包含數組的結構,但數組中的元素是完全錯誤的。我一直在這個網站上搜索一個答案,谷歌,甚至Bing也沒有。我能找到的最好的答案是這樣的:如何返回包含數組的正確元素的結構(來自函數)?
從 How to make an array return type from C function?功能無法在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
請解釋'ca [c.as];' –
爲了完成這項工作,您需要在結構聲明中指定數組大小,它不能基於運行時參數變化 –
@MM感謝您的幫助 –