2016-10-08 63 views
-2

我想通過void函數的引用返回一個動態數組。 我已經搜索了3個小時的答案,找不到任何有用的東西。 這裏是我的簡化代碼:如何從c中的void函數返回動態數組?

main() 
{ 
    int **a; 

    xxx(&a); 

    printf("%d\n\n", a[1]); 

} 

void xxx(int **a) 
{ 
    int i; 

    *a = (int*)malloc(5 * 4); 

    for (i = 0; i < 5; i++) 
     a[i] = i; 
    printf("%d\n\n", a[1]); 
} 

我只是想在「XXX」功能分配動態數組,並參考其返回到主,不是我想要打印或使用別的東西。感謝提前:)

編輯

#include <stdio.h> 
#include <stdlib.h> 
#define MACROs 
#define _CRT_SECURE_NO_WARNINGS 

void xxx(int **a); 


int main(void) 
{ 
    int *a; 

    xxx(&a); 

    printf("%d\n\n", a[1]); 
} 


void xxx(int **a) 
{ 
    int i; 

    *a = malloc(5 * sizeof(**a)); 

    for (i = 0; i < 5; i++) 
     a[i] = i; 
    printf("%d\n\n", a[1]); 
} 
+0

[請參閱此討論關於爲什麼不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+0

你已經很近了,但代碼仍然有很多*錯誤的東西。你應該真的聽你的編譯器,因爲它會向你大喊警告。如果不是,那麼你需要調高警戒級別(無論如何你應該這樣做)。 –

+0

請勿使用「幻數」。或者'#define'(對於數組長度來說),或者使用'sizeof'(對於標準或更復雜的用戶定義類型)。 –

回答

0

在你main(),你需要有一個指針,而不是一個指針的指針。

a[i] = i; 

(*a)[i] = i; 

也就是說

改變

int **a; 

int *a; 

,並在裏面xxx(),改變0

+0

我正在使用新的視覺工作室。我改變了你說的代碼,但它仍然不起作用。 – Jen

+0

@Jen你的編譯器告訴你什麼?一些警告?我已經更新了我的答案,順便說一句。 –

1

我修改了一些東西並添加了一些註釋。

#include <stdio.h>      // please inlcude relevant headers 
#include <stdlib.h> 

#define ELEM 5       // you can change the requirement with a single edit. 

void xxx(int **a)      // defined before called - otherwise declare a prototype 
{ 
    int i; 
    *a = malloc(ELEM * sizeof(int)); // do not use magic numbers, don't cast 
    if(*a == NULL) { 
     exit(1);      // check memory allocation 
    } 
    for (i = 0; i < ELEM; i++) { 
     (*a)[i] = i;     // index correctly 
    } 
} 

int main(void)       // 21st century definition 
{ 
    int *a;        // correct to single * 
    int i; 
    xxx(&a); 
    for (i = 0; i < ELEM; i++) {  // show results afterwards 
     printf("%d ", a[i]); 
    } 
    printf("\n"); 
    free(a);       // for completeness 
} 

程序輸出:

0 1 2 3 4 
-1

好球員,這樣使得它的工作就是

a[i] = i; 

(*a)[i] = i; 

3小時,進行這樣一個簡單的答案。 非常感謝大家。 有些人可以解釋爲什麼這是問題嗎?

+0

那麼,這不是唯一的問題,另一個是'main'中的'int ** a;'。但是'(* a)[i] = i;'引入了額外的必要間接級別,並且重新提到了這個評論的第一點,在'main'中刪除了這個間接性。 –

+0

@WeatherVane在我發佈之前,我試圖改變代碼中的東西,從** a到* a,但沒有任何工作,我嘗試了很多東西,但沒有考慮過這樣做(* a)[i] = i。老實說,我不明白爲什麼這應該是這樣,但無論如何感謝 – Jen