Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the pointer blank when it refers to a value of zero?

Tags:

c++

char

pointers

Playing with pointers in c++. I have come across something unexpected. I have the code:

int main(){
  char p=0;
  char* ptr=&p;
  cout<<"This is the pointer: "<<ptr;
return 0;
}  

When I run this code the output of ptr is blank. If I change the value of p to any other value it seems to output a random pointer, e.g. value changes between runs, as I would expect. The question then is what is different about assigning a char value to 0.
Extra info: compiling with g++ 4.8.4

like image 874
quantomb Avatar asked Dec 13 '25 06:12

quantomb


1 Answers

char p=0;

Your variable is defined as character and assigned an integer value zero, so internally you are assigning a null terminated character on variable p. If you correct above statement as follows and print more details it may be clear to you.

char p='0'; 

std::cout<<"This is the pointer: "<<&ptr<<" ---"<<*ptr <<"----"<<ptr;

&&ptr- > getting the address of ptr

*ptr-> getting the value assigned to the ptr

ptr-> getting the string from ptr until it see a null terminating character, so expects garbage value as output.

Demo: http://coliru.stacked-crooked.com/a/2d134412490ca59a

like image 91
Steephen Avatar answered Dec 15 '25 18:12

Steephen