有关指针以及什么是/不是指针的问题
Questions about pointers and what is/is not a pointer
关于最终指向指针的问题(我怀疑(。请阅读注释代码中提出的问题:
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 *c
和char 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);
相关文章:
- 链表指针问题
- 指针问题:从不兼容的类型"int"分配给"int *"
- C++指针问题:如何修复这些代码中的错误?
- *++*++ppp,*++pp[1],*++(*(1+ppp)有什么具体的区别吗?(C/C++指针问题)
- C++ 入门加列表:10.9 "顶部"指针问题
- C++ 指针问题 - 通过方法更新指针
- 未分配正在释放的指针 - 指针问题
- 双指针问题通过函数传递错误
- 在C++中实现图形 DFS,指针问题
- 返回指针问题
- C++ - 有人有分析指针到指针问题的技巧吗?
- 选择排序指针问题
- 涉及删除操作的 C++ 指针问题
- 模板类指针问题 c++
- Swig和指针问题(python)
- 引用指针问题
- 函数指针问题
- 通过类型C++ 的继承树递归导致此指针问题
- 无法将文件读入字符数组(像往常一样,某些指针问题)
- 结构中的指针问题