的原因,這似乎工作是因爲你正在增加你的指針來指向內存中的新點(你的程序可能被分配或不被分配使用)。我猜你是在堆棧中聲明的,這就是爲什麼你的未定義行爲看起來是「好的」。
我不認爲你明白指針的功能和你使用的語法。備註,以下是等價的:
int arr[ 2 ] = { 1, 2 };
int *pi = &arr;
// The following output is equivalent to...
for (int i = 0; i < 2; i++) {
printf("arr[i] = %d.\n", arr[ i ]);
}
// this.
for (int i = 0; i < 2; i++) {
printf("*(p + i) = %d.\n", *(p + i));
}
考慮這一點,替代實現你的代碼來強調你是如何通過你的陣列以外的索引元素指向新的內存地址。
int *d = (int *)malloc(2 * sizeof(int));
*(d + 0) = 4; // Observe you are accessing the memory location d points to.
*(d + 1) = 5; // Observe you are accessing the memory location d + 4 bytes (or 8 if 64-bit) points to...
*(d + 2) = 8; // ...
*(d + 3) = 9; // ...
*(d + 4) = 7; // Observe you are assigning a value to the memory location of d + 24 bytes (or 48 bytes if 64-bit).
for (int i = 0; i < 5; i++) {
printf("%d \n", *(d + i));
}
只是關於您的代碼的簡短說明。一個malloc通常應該跟隨一個免費的 - 所以適當使用它,所以沒有內存泄漏。
我希望這有助於!如果我犯了一個錯誤,請隨時糾正我。
您的代碼行爲是未定義意味着在不同的執行過程中您可能會注意到不同的行爲,您無法事先預測,您的程序可能會在某個時候崩潰。此代碼錯誤!不幸的是C編譯器不報告這一點。 –