具有空终止符的指针 - 数组交互

Gre*_*ner 3 c++ arrays pointers pointer-arithmetic

我只是在处理数组时尝试使用指针,而且我对C++处理数组的方式感到有些困惑.以下是我写的相关代码:

//declare a string (as a pointer)
char* szString = "Randy";               

cout << "Display string using a pointer: ";
char* pszString = szString;
while (*pszString)
cout << *pszString++;
Run Code Online (Sandbox Code Playgroud)

首先,当我尝试使用cout来编写"pszString"中的内容时(没有取消引用)我有点惊讶地看到它给了我字符串.我只是假设它是因为我给指针一个字符串而不是一个变量.

真正吸引我注意的是,当我从行中删除星号时,cout << *pszString++;它打印出"Randyandyndydyy".我不确定为什么它会写入数组然后再用1个字母再写一次.我的理由是,在写入字符串后,增量运算符会立即将索引带到下一个字母,然后才能到达空终止符.我不明白为什么null终止符不会导致循环在第一次输出字符串后返回false,否则.这是正确的推理吗?有人可以解释我是否在数组和指针之间得到这种关系?

Set*_*gie 6

cout有一个operator<<重载char*打印整个字符串(即打印每个字符,直到它遇到一个0).相比之下,'s 的char重载只打印了一个字符.这基本上就是这里的差异.如果您需要更多解释,请继续阅读.coutoperator<<

当你提领递增之后的指针,你发送cout一个char,char*,所以它打印一个字符.

所以,cout << *pszString++;就像是在做

cout << *pszString;
pszString = pszString + 1;
Run Code Online (Sandbox Code Playgroud)

当你取消引用指针时,你发送它char*就是cout打印整个字符串,并且你在每次迭代中通过循环将字符串的开头向上移动一个字符.

所以,cout << pszString++;就像是在做

cout << pszString;
pszString = pszString + 1;
Run Code Online (Sandbox Code Playgroud)


展开一个小循环的插图:

对于 cout << *pszString++;

Randy\0
^ 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\0
 ^ 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\0
  ^ here

// and so on
Run Code Online (Sandbox Code Playgroud)

对于 cout << pszString++;

Randy\0
^ 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\0
 ^ here

cout << pszString++;

// cout prints andy, and now pszString points
Randy\0
  ^ here

// and so on
Run Code Online (Sandbox Code Playgroud)

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