[英]How does the memory layout look like when a double pointer is assigned to a single pointer?
I am currently working on a legacy code (still proprietary, so we'll have to make do with an MRE instead; and by legacy I mean code written in 1991).我目前正在处理遗留代码(仍然是专有的,所以我们必须使用 MRE 来代替;我所说的遗留代码是指 1991 年编写的代码)。 This is what I've come across:
这就是我遇到的情况:
#include <iostream>
void foo(void*& ptr2) {
// whatever
}
int main() {
int** ptr = new int*[5];
void* ptr2;
int i = 1;
for(int j = 0; j < 5; j++) {
ptr[j] = new int;
ptr[j][0] = i++;
}
ptr2 = ptr;
foo(ptr2);
// further operations here... and a comment which suggests the above was done to prevent accidental double dereferencing when ptr2 was passed by reference to another function
return 0;
}
How does the logical layout of ptr2
look like in this case?在这种情况下,
ptr2
的逻辑布局如何? I am assuming that ptr[0][0]
becomes ptr2[0]
, ptr[1][0]
becomes ptr2[1]
and so on, but the print statements (not required in the MRE, just standard cout statements on various indices) prove my assumption wrong.我假设
ptr[0][0]
变成ptr2[0]
, ptr[1][0]
变成ptr2[1]
等等,但是打印语句(MRE 不需要,只是各种标准的 cout 语句指数)证明我的假设是错误的。 What am I missing here?我在这里错过了什么?
The question is pretty unclear but I will try to answer anyway:这个问题还不清楚,但我还是会尝试回答:
new int *[5]
is 5 contiguous pointers each of type int *
. new int *[5]
分配的对象的布局是 5 个连续的指针,每个都是int *
类型。 Mucking around with other pointers that point to this memory block does not change the layout of this memory block. Inside foo
, the memory that was allocated by new int *[5]
can be accessed by recovering its address with the correct type:在
foo
内部,可以通过使用正确类型恢复其地址来访问由new int *[5]
分配的 memory:
void foo(void*& ptr2)
{
int **ptr = static_cast<int **>(ptr2);
for(int j = 0; j < 5; j++)
std::cout << ptr[j] << '\n';
}
Any other ways of attempting to access the memory block in question cause undefined behaviour.尝试访问有问题的 memory 块的任何其他方式都会导致未定义的行为。 (Well, except for aliasing it as
unsigned char
). (好吧,除了别名为
unsigned char
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.