小编BnE*_*BnE的帖子

为什么指向c-string中元素的指针不返回元素?

我试图理解指针在这里是如何工作的.该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)

c++ string pointers c-strings

4
推荐指数
1
解决办法
251
查看次数

标签 统计

c++ ×1

c-strings ×1

pointers ×1

string ×1