why char is considered as Bad Pointer?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include<iostream>
using namespace std;
int main()
{



	char x=97;
	char *yptr;
	yptr = &x;
	cout<<yptr<<endl;
	cout<<*yptr<<endl;
	*yptr++;
	cout<<*yptr<<endl;
         sytem("pause");
         return 0;
}
yptr is set to the address of x.

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.
so ++ will occur first

Not to nit-pick, but the ++ operator is more tightly bound to the operant than the * operator. So the difference is in what is being incremented.

*ptr++
Both * and ++ are bound to ptr, so the result of evaluation is 'return object addressed by ptr and increment ptr.

(*ptr)++
Now * is still bound to ptr, but ++ is bound to 'object addressed by ptr, so evaluation is 'access object addressed by ptr and increment it'.

In both cases the increment happens last.

I know Thumper knows this, I just want to clarify for OP.

Hope this helps.
thanks. plz explain bad pointer too.
when im debugging the code
char *yptr;
is considered as bad pointer.
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.
Topic archived. No new replies allowed.