2016-11-28 75 views
-4

你好,我有一個函數的問題。聲明是:帶兩個指針的C函數

int load_clusters(char *filename, struct cluster_t **arr) 

而且我不知道如何在** arr之前使用這兩個指針。 我希望我這樣稱呼它:

struct cluster_t *clusters; 
load_clusters("file.txt",&clusters); 

但我不知道這是否是正確與否。

在函數中我需要爲它分配內存。 我認爲它必須是這樣的。

arr = (struct cluster_t**)malloc(count * sizeof(struct cluster_t*)); 
arr[0...x] = (struct cluster_t*)malloc(sizeof(struct cluster_t)); 
arr[0...x]->size += 1; 
. 
. 
. 

但畢竟這需要調用函數來打印集羣。

void print_clusters(struct cluster_t *carr, int narr) 
{ 
    printf("Clusters:\n"); 
    for (int i = 0; i < narr; i++) 
    { 
     printf("cluster %d: ", i); 
     print_cluster(&carr[i]); AND THIS DOESN'T WORK AS I EXPECT 
    } 
} 

感謝所有幫助;-)

+1

通常,**表示該函數將分配內存,並希望返回一個指向已分配內存的指針,因此您需要將指針傳遞給指針。 – stark

回答

0

在功能load_clustersarr是一個局部變量,所以它所做的任何更改都不會反映在調用者。

你有什麼是你想分配給指針變量的地址。所以取消引用併爲struct cluster_t的數組分配空間。

*arr = malloc(count * sizeof(struct cluster_t)); 

另外,don't cast the return value of malloc