指针-数组交互,无终止符
Pointer-Array Interaction w/ null terminator
我只是在处理数组时尝试使用指针,我对c++如何处理数组有点困惑。以下是我编写的相关代码:
//declare a string (as a pointer)
char* szString = "Randy";
cout << "Display string using a pointer: ";
char* pszString = szString;
while (*pszString)
cout << *pszString++;
首先,当我尝试使用cout来写"pszString"中的内容(没有取消引用)时,我有点惊讶地看到它给了我字符串。我只是假设它是,因为我给指针一个字符串,而不是一个变量。
真正引起我注意的是,当我从cout << *pszString++;
行删除星号时,它显示了"Randyandyndydyy"。我不知道为什么它写数组,然后再写1个字母少。我的理由是,在写入字符串后,增量运算符立即将索引带到下一个字母,然后才能到达空终止符。我不明白为什么空终止符不会导致循环在字符串第一次输出后返回false。这是正确的推理吗?有人能解释一下数组和指针之间的关系吗?
cout
对char*
具有operator<<
过载以打印整个字符串(即打印每个字符直到遇到0
)。相比之下,cout
的operator<<
的char
重载只打印一个字符。这就是本质上的区别。如果你需要更多的解释,请往下读。
当你对指针加1后解引用时,你向cout
发送了char
, 而不是和char*
,所以它打印一个字符。
所以cout << *pszString++;
就像做
cout << *pszString;
pszString = pszString + 1;
当你没有对指针解引用时,你给它发送了一个char*
,所以cout
打印整个字符串,并且你在循环的每次迭代中将字符串的开头移动一个字符。
所以cout << pszString++;
就像做
cout << pszString;
pszString = pszString + 1;
带有小循环展开的插图:
For cout << *pszString++;
Randy
^ pszString points here
// this means increment pszString and send cout the character at which pszString *used* to be pointing
cout << *pszString++;
// so cout prints R and pszString now points
Randy
^ here
// this means increment pszString and send cout the character at which pszString *used* to be pointing
cout << *pszString++;
// so cout prints a and pszString now points
Randy
^ here
// and so on
For cout << pszString++;
Randy
^ pszString points here
// this means increment pszString and pass the old pointer to cout's operator<<
cout << pszString++;
// so cout prints Randy, and now pszString points
Randy
^ here
cout << pszString++;
// cout prints andy, and now pszString points
Randy
^ here
// and so on
我很高兴你用这种方式来尝试指针,它会让你真正知道发生了什么,不像许多程序员会做任何事情来摆脱必须处理指针。
相关文章:
- Qt VTK交互风格的信号到小部件
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- C++中无符号字符溢出
- 终止无主动例外的终止
- 如何在无符号 N 位交互器中修复二进制点的位置
- 在字符串附加函数中,null终止无符号字符缓冲区的有效方法
- 指针-数组交互,无终止符