2016-12-31 99 views
-1

我需要通過動態內存分配構建一個指向int的指針數組。 我開始聲明:指針陣列的問題

int** queue = (int**)malloc(sizeof(int*)); 

和大於(尺寸= 1)

queue[*size-1] = (int*)calloc(1,sizeof(int)); 

我掃描的整數:

printf("Enter item value to add\n"); 
    scanf("%d",queue[*size-1]); 
    printf("Item %d added\n",*(queue[*size-1])); 

所有這些代碼是在相同的功能和工作正常。 但是當我嘗試從這個隊列中的另一個功能打印的東西或釋放內存:

for(i = 0;i<size;i++) 
    { 
     free(queue[i]); 
    } 
    free(queue); 

程序崩潰。 我想獲得一些幫助。 在此先感謝!

+2

是'* size-1'應該是'(* size)-1'還是'*(size-1)'? (請參閱[運算符優先順序](http://en.cppreference.com/w/c/language/operator_precedence))。另外[不要施放'malloc']的返回值(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – UnholySheep

+3

還有什麼'size'聲明爲?從你的解釋看來,它似乎是一個單一的整數值,在這種情況下,我不明白爲什麼它通過指針 – UnholySheep

+0

來訪問其應該是(* size)-1 –

回答

1
int** queue = (int**)malloc(sizeof(int*)); 

將只分配足夠的內存來保存一個元素,所以如果大小爲2或更高,你會在你還沒有分配,所以你會得到undifenied行爲(例如崩潰)的隊列地址memeory。

如果你想分配內存的隊列爲10,你需要分配足夠的內存;

int** queue = (int**)malloc(sizeof(int*) * 10); 

enter image description here

你需要做的紅色部分足夠長,以容納所有的元素,隊列指向該元素的開始。

如果你不想讓隊列長度固定,你可以使用realloc的,像

int** queue = (int**)realloc(queue, sizeof(int*) * ((*size)+1)); // resize red part 
queue[(*size)-1] = (int*)calloc(1,sizeof(int)); // Creating the green part 

在這裏,我從你的代碼的其餘部分假設大小是一個int *size

+0

upvote,但你用什麼編輯器繪製圖像? – coderredoc

+0

如果用戶選擇將另一個項目添加到隊列中,我確實使用了realloc。 –

+0

@coderredoc - 即谷歌圖紙 – Soren