user691197 user691197 - 5 months ago 40
C Question

C - Basic Pointer questions

It has been a long time since I worked on C, so revisiting it now.

Can you help me with explaining what value does 'ptr' carry in below code ?

char str[] = "100";
char *ptr;
ptr = *str;
printf("\n %p \t %d \n", ptr, ptr);

Output shows:

0x31 49

I know that assigning *str to ptr is not correct, I'd however want to understand what that would actually mean. So what does 49 stand here ?


C is very forgiving in assigning values to variables of different kinds. That is why you don't get an error, even though you should!
So you are assigning *str, or, whatever str points to, to ptr. str is a char pointer, so it points to a char, in this case, the '1' in "100".

That, then, is the value you assign to ptr, the value '1' or 49. (At least in an ASCII based system. On another system you would get a different value for '1'. For instance on an EBCDIC machine, '1' would be 241 instead of 49.)

And then you are trying to print the value of ptr, first as a pointer, which displays the numerical value of a pointer in hex, and then as a decimal, which simply displays the numerical value.

Now it's a good thing you're not trying to print *ptr, because that would have gone horribly wrong!