指针-数组交互,无终止符

Pointer-Array Interaction w/ null terminator

本文关键字:无终止 交互 数组 指针      更新时间:2023-10-16

我只是在处理数组时尝试使用指针,我对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。这是正确的推理吗?有人能解释一下数组和指针之间的关系吗?

coutchar*具有operator<<过载以打印整个字符串(即打印每个字符直到遇到0)。相比之下,coutoperator<<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

我很高兴你用这种方式来尝试指针,它会让你真正知道发生了什么,不像许多程序员会做任何事情来摆脱必须处理指针。