Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to a pointer

Tags:

c++

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?

like image 779
user3234 Avatar asked Feb 17 '11 09:02

user3234


4 Answers

why does it fails with access violation error?

[] have precedence over * . You need to first dereference x

(*x)[0] = 1;
(*x)[1] = 1;
like image 151
nos Avatar answered Oct 22 '22 00:10

nos


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.

like image 20
templatetypedef Avatar answered Oct 22 '22 00:10

templatetypedef


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)[].

like image 21
grzkv Avatar answered Oct 22 '22 00:10

grzkv


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;
like image 44
CashCow Avatar answered Oct 22 '22 02:10

CashCow