有代码:
int** a = new int*[2];
a[0] = new int(1);
a[1] = new int(2);
cout << "a[0] " << a[0] << '\n';
cout << "a[1] " << a[1] << '\n';
cout << "a[2] " << a[2] << '\n';
cout << "a[0] + 1 " << a[0] + 1 << '\n';//WHY THIS ISN'T == a[1] ?
cout << "*(a + 1): " << *(a + 1) << '\n'; //WHY THIS IS == a[1] ?
cout << "a[0] - a[1] " << static_cast<int>(a[0] - a[1])<< '\n';//WHY THIS IS == 16 not 4?
cout << sizeof(int**);
Run Code Online (Sandbox Code Playgroud)
问题包含在代码中的相关行旁边.
a[0]并且a[1]它们是连续的,它们都是指针,但它们并不指向连续的记忆区域.
那是因为new运营商返回的内存指针实际上是不可预测的.
换句话说,没有保证(实际上完全相反)返回的内存块
a[0] = new int(1);
a[1] = new int(2);
Run Code Online (Sandbox Code Playgroud)
是连续的.