pointer declaration and initialization

If i write a statement as
int *ptr=0;
Does it mean that the address of ptr is zero???
Because we all are very well familiar that the code
1
2
int i;
int *ptr=&i;

means that ptr has been assigned a address of i...
If i write a statement as
int *ptr=0;
Does it mean that the address of ptr is zero???


No. The address of an object is the location in memory where it is. What this does is set the value of the pointer to zero. Somewhere in memory is the pointer named ptr, and if you look at that pointer, it has the number zero in it.

1
2
int i;
int *ptr=&i;


means that ptr has been assigned a address of i...

That's correct. Now, the pointer holds a number which is the number of the place in memory when you will find the int named i.

If this is confusing, here is what I usually write about pointers: http://www.cplusplus.com/articles/EN3hAqkS/
Last edited on
If you want to see the actual address just cout the pointer without using *. It will be in the form of a hex number.

There is also a difference between

*ptr = &i;

and

ptr = &i;


You can use cout statements to see what's happening and it's a great way to learn.
Last edited on
No. The address of an object is the location in memory where it is. What this does is set the value of the pointer to zero. Somewhere in memory is the pointer named ptr, and if you look at that pointer, it has the number zero in it.



So does it mean that ptr is a NULL pointer???
Pointers in C++ don't really have default values so unless you set them to NULL explicitly they could be pointing to garbage.
It means that the pointer has null pointer value.:)
Topic archived. No new replies allowed.