Pointer to a pointer
I'm trying to set the memory of pointer p
through pointer to pointer x
int *p = 0;
int **x = &p;
*x = new int[2];
*x[0] = 1; //p[0] = 1
*x[1] = 2; //p[1] = 2
开发者_C百科
why does it fails with access violation error?
why does it fails with access violation error?
[] have precedence over * . You need to first dereference x
(*x)[0] = 1;
(*x)[1] = 1;
I think your problem is that
*x[1]
Means
*(x[1])
And not
(*x)[1]
This second version is what you want; it dereferences the pointer to get the underlying array, then reads the second element. The code you have now treats your double pointer as a pointer to the second element of an array of pointers, looks up the first pointer in it, then tries dereferencing it. This isn't what you want, since the pointer only points at one pointer, not two. Explicitly parenthesizing this code should resolve this.
In the expression like *A[]
the variable A
is first indexed and then dereferenced, and you want exactly the opposite, so you need to write (*A)[]
.
Unfortunately the type-safe system doesn't help you here.
x[0] and x[1] are both of type int* so you can do
*(x[0]) = 1; // allowed
*(x[1]) = 2; // access violation, not through x[1] itself but by accessing it
Of course your intention was
(*x)[0] = 1;
(*x)[1] = 2;
FYI, You can also try accessing memory locations pointed by x
in this way too -
x[0][0] = 1;
x[0][1] = 2;
Your problem is that you have set p to the address of 0. You have not actually allocated any space for p (and therefore x.) So you are trying to set the memory at address 0 and 1. If you change it to this, it should work without the error.
int *p = new int[5];
int **x = &p;
*x = new int[2];
(*x)[0] = 1; //p[0] = 1
(*x)[1] = 2; //p[1] = 2
精彩评论