我试图理解指针在这里是如何工作的.该findTheChar功能搜索str该角色chr.如果chr找到,则返回指向str首次找到字符的指针,否则nullptr(未找到).我的问题是为什么函数打印"llo"而不是"l"?虽然我写的代码main返回"e"而不是"ello"?
#include <iostream>
using namespace std;
const char* findTheChar(const char* str, char chr)
{
while (*str != 0)
{
if (*str == chr)
return str;
str++;
}
return nullptr;
}
int main()
{
char x[6] = "hello";
char* ptr = x;
while (*ptr != 0)
{
if (*ptr == x[1])
cout << *ptr << endl; //returns e
ptr++; …Run Code Online (Sandbox Code Playgroud)