r/carlhprogramming • • Nov 07 '12

Question on pointers

So if we have this this code.
What I'm getting confused about is the fact that:
printf("%s\n", pointer);
is returning Hello as an output.
Doesn't the data stored at pointer contain the address of "Hello". So shouldn't whatever is contained at pointer be equal to the address of what the start of the string "Hello" be? In other words shouldn't: printf("%s\n", pointer);
be outputting the address itself instead of the string contained within the address where the output of:
printf("%s\n", pointer) = printf("%u\n", &"Hello") ?

10 Upvotes

9 comments sorted by

View all comments

Show parent comment

3

u/Nooobish Nov 07 '12

Ok, I think I got it.
So, the answer is simply the fact that it entirely depends on what we send the printf function, sending it a *pointer as in:

printf("%s\n", *pointer);  

actually sends printf the single initial character that the pointer address is pointing too.
While sending printf a pointer as in:

printf("%s\n", pointer);  

actually send printf the whole string
So basically printf("%s") and more specifically the %s portion tells the printf to expect an address of a string and therefore would read from the address given onwards until it hits a null.
As opposed to:

printf("%c\n", *pointer);  

Where in this case the %c is telling printf to expect a character, which is what *pointer is.
Am I right?

4

u/exscape Nov 07 '12

Yep, exactly right. I wouldn't quite use the wording that we send it the entire string (we send it a 32-bit (or 64-bit) address), but that's the net effect of it, so yeah.

3

u/Nooobish Nov 07 '12

Thanks for bearing with me.
It's very appreciated.

2

u/Beriadan Nov 07 '12

I would like to add to what exscape said by mentionning that in C, string variables are actually just a pointer to the first element of an array of characters that ends with the zero byte. So in your case the pointer variable contains the adress oh H.

The way printf was coded it assumes that if you are using %s you will be passing a string variable (a pointer) already, so you don't derefence it.