简体   繁体   中英

I don't understand this use of pointers

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++);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM