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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With