私は現在、動的メモリ割り当てを学ぶためにC++ prime plusを読んでいました。私はその本でコードを試しましたが、後ろに1行追加した後、私は私が得たものに混乱しました。私はp3のメモリを解放して実際にプリントアウトした後、p3 [2] p3の正しい値しかし、すでにメモリを解放した後に印刷することは不可能ではないでしょうか?ここでC++素数と動的配列の例の混乱
はコードです:
// arraynew.cpp -- using the new operator for arrays
#include <iostream>
int main() {
using namespace std;
double * p3 = new double [3]; // space for 3 doubles
p3[0] = 0.2; // treat p3 like an array name
p3[1] = 0.5;
p3[2] = 0.8;
cout << "p3[1] is " << p3[1] << ".\n";
p3 = p3 + 1; // increment the pointer
cout << "Now p3[0] is " << p3[0] << " and ";
cout << "p3[1] is " << p3[1] << ".\n";
cout << "p3[2] is " << p3[2] << ".\n";
p3 = p3 - 1; // point back to beginning
delete [] p3; // free the memory
cout << "p3[2] is " << p3[2] << ".\n";
return 0;
}
p3[1] is 0.5.
Now p3[0] is 0.5 and p3[1] is 0.8.
p3[2] is 6.95326e-310.
p3[2] is 0.8.
出力の実際のテキストを投稿してください。スクリーンショットではありません。 (出力が非常に小さいので、今回はあなたのために編集しました)。 – BoBTFish
未定義の動作が発生しました。言葉のように、そのようなことの結果は未定義です。 – 101010
その実際のC++ Primer Plus –