有关指针以及什么是/不是指针的问题

Questions about pointers and what is/is not a pointer

本文关键字:指针 问题 什么      更新时间:2023-10-16

关于最终指向指针的问题(我怀疑(。请阅读注释代码中提出的问题:

void doodah(char* a);
int main() {
    char d[] = "message"; // one way of assigning a string.
    // char* d = "message"; // another way of assigning a string, but REM'ed out for now.
    cout << d << endl; // d appears not to be a pointer because cout outputs "message", and not an address. Why is this?
    doodah(d); // a function call.
}
void doodah(char* a) {
    cout << a << endl; // this outputs "message" - but why?! What does 'a' mean in this context?
    // cout << *a << endl; // this outputs "m" - but why?! REM'ed out for now.
}

我完全糊涂了!请帮忙。

cout知道如何在给定char *时输出字符串。它不会尝试打印指针值本身。

数组是内存中某处彼此相邻的一堆对象。您设置数组的变量实际上是秘密地指向该数组中第一项的指针(嘘!

char *cchar c[]的最大区别在于后者将是一个const指针,而前者可以自由更改。此外,C 字符串,就像你在那里设置的一样,是 null 终止的,这意味着数组以二进制 0 结尾,所以像 cout 这样的东西会知道什么时候停止迭代(这也称为最后一次传递(。

有关更多信息,您可以阅读此问题。

这是

指针a在内存中的样子:

-------------------------------------------------------------
|      | 'm' | 'e' | 's' | 's' | 'a' | 'g' | 'e' | ''     |
|         ^                                                 |
|         |                                                 |
|        ---                                                |
|        |a|                                                |
|        ---                                                |
-------------------------------------------------------------

a 是指向字符串的第一个元素的指针。当在流插入器(operator<<()(中使用时,编译器将它与重载相匹配,重载在其左侧获取流,在其右侧获取指向字符的指针。然后,它将尝试打印每个字符,直到它到达空字节(''(,方法是计算来自a的增量地址的字符。

流通过在其右侧取void*的重载打印地址。您可以将指针投射到void*或使用标准提供的std::addressof()函数:

std::cout << std::addressof(a);