我想完全包圍malloc和內存分配。我最近遇到了一個讓我擡頭的情況。Malloc不需要創建內部陣列
當擺弄數組時,我創建了一個數組數組。在我的腦海中會看起來像這樣: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], ...]
當我這樣做時,我想到因爲我需要malloc來創建外部數組。我還需要爲我創建的每個內部數組調用malloc。我很快意識到,當我跳過這一步對我沒有意義時,我會得到相同的輸出。
請考慮以下腳本。
int main(int argv, char* argc[]){
// initialize outer array
int* outer = malloc(5 * sizeof(int));
int i, j;
// for each slot in outer array
// create a new array and assign it
// to that slot.
// NOT NEEDED.
for(i = 0; i < 5; i++){
int* inner = malloc(5 * sizeof(int));
*(outer + i) = *inner;
}
// If I comment out the above four lines
// the output remains the same.
// assign to each slot in each inner array
for(i = 0; i < 5; i++)
for(j = 0; j < 5; j++)
*(outer + i * 5 + j) = j;
// print each element in each inner array
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
printf(
"%d ",
*(outer + i * 5 + j)
);
}
puts("");
}
}
從該腳本的輸出如下:
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
這是我所期待的。但是當我在腳本中註釋掉第一個for循環時,我會得到相同的輸出。爲什麼是這樣?我不需要爲內部數組分配內存嗎?很明顯,答案是否定的,但我試圖理解這是爲什麼。
這背後的想法到底是什麼:'...... = * inner;'? – alk
@alk爲外部數組中的那個索引分配一個新的內存空間。 – marcusshep
可能是,即使問題是C++有所幫助:http://stackoverflow.com/questions/4316736/using-unallocated-memory-without-error – Cherubim