2016-10-04 70 views
1

我正在做一個程序,返回一個包含數組的結構,但數組中的元素是完全錯誤的。我一直在這個網站上搜索一個答案,谷歌,甚至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 
+0

請解釋'ca [c.as];' –

+0

爲了完成這項工作,您需要在結構聲明中指定數組大小,它不能基於運行時參數變化 –

+0

@MM感謝您的幫助 –

回答

1

struct具有靈活性的值不能被值操縱,只能通過指針操縱。

您不能使用靈活的成員按值返回struct,因爲C不知道需要分配給返回值的項數以及需要複製的字節數。

分配您struct使用足夠大小的malloc動態內存,您的數據複製到它,並且指針返回給調用者:

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; 

改變你的函數返回一個指針;確保調用者釋放結果。

+0

測試和工作很好,感謝編寫代碼,幫助我更好地理解它 –

1

在你的函數,struct Codes create(int as),該struct Codes c;分配上卡住,所以內存是不再有效一旦函數返回...

...的確,核心結構是複製到返回值中...但變量數組長度c.a不是結構體的一部分(它是內存「尾部」或「尾部」),並且不會與返回值一起復制。

或者:

  1. 分配結構並將它傳遞給一個struct Codes create(struct Codes *dest, int as)功能; OR

  2. 使結構數組大小固定struct Codes{ int as; int a[4]; };

好運。

+0

測試完方式,我現在明白了,謝謝 –

相關問題