2010-11-14 73 views
2

我想分配和初始化一個函數內的數組,但我似乎無法在返回後取值。在c函數中分配數組

這是我最後幾乎工作嘗試

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int func(int **thing); 

int main() { 

int *thing; 

func(&thing); 

printf("%d %d", thing[0], thing[1]); 
} 

int func(int **thing) { 

*thing = calloc(2, sizeof(int)); 

*thing[0] = 1; 
*thing[1] = 2; 

printf("func - %d %d \n", *thing[0], *thing[1]); 
} 

,但打印的功能以外的值是1和0 有很多指針上的文件在那裏,但我還沒有發現這種特定的案件涵蓋。關於我在做什麼的任何提示都是錯誤的?

+2

由於運算符的優先級,可能有問題嗎?我會嘗試用「(* thing)[x]」替換所有「* thing [x]」。 – Bwmat 2010-11-14 19:43:48

回答

5

而不是一個指針傳遞到指針,您可能會發現更容易將新分配的數組從你的函數返回:

int *func(); 

int main() { 

int *thing; 

thing = func(); 

printf("%d %d", thing[0], thing[1]); 
} 

int *func() { 

int *thing; 

thing = calloc(2, sizeof(int)); 

thing[0] = 1; 
thing[1] = 2; 

printf("func - %d %d \n", thing[0], thing[1]); 

return thing; 
} 

您的代碼不工作的原因是因爲這樣的:

*thing[0] 

由於符的優先級,你應該使用:

(*thing)[0] 
5

的上一頁*[]的數字是這樣的,你的作業意味着*(thing[0])。你需要明確的加入,如(*thing)[0]

3

Inside func(),*thing[n]相當於*(thing[n]),即*(*(thing + n)),即數組索引優先於取消引用。您需要使用(*thing)[n]進行分配。

1

[]比去反射具有更高的優先級。使用明確paranthesis:(*thing)[0] = 1;

0

使用()爲正確的優先級之後,不要忘記改變*thing = calloc(2, sizeof(int));thing = calloc(2, sizeof(*int));併爲thing元素分配內存,因爲它的元素是指向整數。