How to properly declare and then assign a value to a pointer ?

I have a code where the following works:


1
2
3
4
5
6
//code 1
int* p1 = &v1;
int* p2 = &v2;
.
.
.


But the following doesn't:

1
2
3
4
5
6
7
//code 2
int *p1, *p2, ...;
*p1 = &v1;
*p2 = &v2
.
.
.


Why not ? And what is the proper way to reproduce the result of code 1 while still declaring the pointers first as in code 2 ?
1
2
3
4
int *p1;    // p1 contains a garbage value
*p1 = &v1;  // store address of v1 in the location which is pointed to by p1
            // since p1 is not initialised with a valid address, 
            // that also tries to use an invalid pointer 


You don't need to dereference the pointer with an * when assigning a new value:
1
2
int *p1 = nullptr; // assign initial value
p1 = &v1; // store address of v1 in the pointer p1 (replaces nullptr) 

The way to look at this is that the type is int* (a pointer to int) and the variable is p. You may adjust the spacing to emphasise that meaning int* p1 though the compiler doesn't see the difference).

Last edited on
Thanks, I figured that and applied too but there seems to be a problem. For example, please have a look at this http://www.cplusplus.com/forum/general/205289/
Topic archived. No new replies allowed.