2011-08-23 49 views
0

我想分配內存指向對象的指針數組。 ObjectP是一個指向結構名爲Object的指針。 在函數之前,我在數組上聲明:ObjectP *數組。所以數組是指向對象指針數組的指針。 然後我發送&數組,所以我會有一個指向它的指針。 說我的table_size是2.我嘗試輸入* array [1] = NULL時出現分段錯誤。 問題是什麼?Segmantation故障 - C使用malloc

這是我的代碼:

void allocateArrayMemory(ObjectP** array,size_t table_size) 
    { 
    *array=(ObjectP*)malloc(table_size*sizeof(ObjectP)); 
    int i=0; 
    for (i = 0; i < (int)table_size; ++i) 
    { 
     *array[i]=NULL; 
     printf("%d\n",i); 
    } 
    printf("finished allocating\n"); 
    if(*array==NULL) 
    { 
     printf("null\n"); 
    } 

    } 
+1

請編輯您的問題,並調整格式。 –

+1

嘗試'(* array)[i] = NULL;'。 –

回答

1

代碼*array[i]=NULL;被表現得像*(array[i])=NULL;和你想要的是(*array)[i]=NULL;

在i = 1,*(array[i])取消引用下面的struct Object ***struct Object ***你傳遞到allocateArrayMemory,而(*array)[i]取消引用在新鮮malloc內存區域中的第二struct Object **

一些注意事項:

  1. 修復 '分割' 的標題中的拼寫。

  2. 使用前測試malloc的結果。在你的代碼中,你使用* array後有一個測試;把它往上移。我建議使用memset(*array, 0, table_size*sizeof(ObjectP));而不是循環來初始化*數組。

  3. 這是C中的錯誤形式來施放malloc結果。相反,只要說*array = malloc(table_size*sizeof(ObjectP));

  4. 作爲一個風格問題,我不得不allocateArrayMemory是返回分配內存的地址的功能,而不是通過參數。例如:

    ObjectP* allocateArrayMemory(size_t table_size) {

    ObjectP *array = malloc(table_size*sizeof(ObjectP));

    ...

    if(array==NULL) { printf ...; return NULL; }

    ...

    for (i=0; i < table_size; ++i)

    { 
    

    array[i] = NULL;

    ...

    } 
    

    ...

    return array;

和來電,ObjectP *a; ... a = allocateArrayMemory(6);