Reputation: 121
I'm trying to understand this use of pointers. From what I realized so far the value pointers hold is a reference to the memory address of another entity, and when using the *
sign we access the value of the entity referenced by the pointer.
However, in this code that I encountered in the tutorial i'm using, the ptr_str
pointer has a string value which is not a memory address, so I don't understand how *ptr_str
(which I expected to be the value of a referenced entity) is used in the for loop.
char *ptr_str; int i;
ptr_str = "Assign a string to a pointer.";
for (i=0; *ptr_str; i++)
printf("%c", *ptr_str++);
Upvotes: 0
Views: 89
Reputation: 69276
This:
ptr_str = "Assign a string to a pointer.";
Is a shorthand for this:
// Somewhere else:
char real_str[] = {'A', 's', 's', 'i', 'g', ..., '.', '\0'};
// In your main():
ptr_str = real_str;
// or
ptr_str = &real_str[0];
In other words, string literals like "Hello World"
are actually pointers to a character array holding your string. This is all done transparently by the compiler, so it might be confusing at first sight.
If you're curious, take a look at this other answer of mine, where I explain this in more detail.
Upvotes: 2