Pointer to pointer

I am 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 fail with an access violation error?

+6
c ++
source share
6 answers

why does it fail with an access violation error?

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

 (*x)[0] = 1; (*x)[1] = 1; 
+12
source share

I think your problem is that

 *x[1] 

Facilities

 *(x[1]) 

And not

 (*x)[1] 

This second version is what you want; it pokes the pointer to get the base array, and then reads the second element. The code you are using now treats your double pointer as a pointer to the second element of an array of pointers, looks at the first pointer in it, and then tries to dereference it. This is not what you want as the pointer points to only one pointer, not two. Explicitly enclosing this code in parentheses should solve this problem.

+5
source share

In an expression of type *A[] variable A first indexed and then dereferenced, and you want the exact opposite, so you need to write (*A)[] .

+2
source share

Unfortunately, a type system will not help you here.

x [0] and x [1] are both int * types, 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; 
+2
source share

FYI, you can also try to access the memory locations indicated by x in the same way -

 x[0][0] = 1; x[0][1] = 2; 
+1
source share

Your problem is that you set p to address 0. You have not actually allocated space for p (and therefore x.). Thus, you are trying to install memory at addresses 0 and 1. If you change it to this, it should work without 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 
+1
source share

All Articles