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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With