简体   繁体   English

我不明白指针的这种用法

[英]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.据我所知,到目前为止,值指针持有的是对另一个实体的 memory 地址的引用,当使用*符号时,我们访问指针引用的实体的值。

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.但是,在我正在使用的教程中遇到的这段代码中, ptr_str指针的字符串值不是 memory 地址,所以我不明白*ptr_str (我希望它是引用的值entity) 在 for 循环中使用。

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.换句话说,像"Hello World"这样的字符串文字实际上是指向保存字符串的字符数组的指针。 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.如果您好奇,请查看我的另一个答案,我在其中更详细地解释了这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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