Hello everyone. I wrote this simple code below just for an experiment.The pointer are fine if im using int or float data type. But for char the yptr is showed as bad pointer during debugging. and its also printing the strange things.
What is the reason for this? Thanks
cout << yptr << endl; Outputs the address of x, which is going to be a weird looking memory location.
cout << *yptr << endl; will output the value stored at the address of x, which is a char value of 97 (the character 'a').
*yptr++ doesn't do what you want it to do. operator ++ takes precedence over operator *, so ++ will occur first. yptr is incremented, meaning it's no longer pointing to the value of x, then yptr is dereferenced, but never used. cout << *yptr << endl; now has some garbage value that's already in memory and is meaningless.
What you want to do here is (*yptr)++. The parentheses force the dereference first, then you increment the value yptr points to.
char *yptr by itself is an invalid pointer because it isn't initialized and points to some random memory location with garbage data. It becomes a valid pointer when you assign it the address of x in the following line.