Why doesn't a pointer to an element in a c-string return only an element?

I am trying to understand how pointers work here. The findTheCharfunction searches strfor a character chr. If found chr, it returns a pointer to strwhere the character was first found, otherwise nullptr(not found). My question is why the function prints "llo"instead "l"? while the code that I wrote in mainreturns "e"instead "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++;
    }
    cout << findTheChar("hello", 'l') << endl; // returns llo
}
+4
source share
5 answers
cout << findTheChar("hello", 'l') << endl; //returns llo

findTheChar - const char *. const char * std::cout , , \0.

str -> +---+---+---+---+---+---+
       | h | e | l | l | o | \0|
       +---+---+---+---+---+---+
                 ^
                 |
         findTheChar(str, 'l')

, ( ). , void *.

, , "e" "ello"

cout << *ptr << endl; //returns e

ptr *ptr , , char, const char *.

++, std::string .

// Returns offset of first occurance if found
// Returns -1 if not found
int findTheChar(const std::string& str, char chr );
+3

C- - , '\0'. .

, , , , , '\0'. operator<< std::cout , , C-. .

, .

+5

, "llo" "l"?

, , .

- : const char*.

cout , , (a char), , C-string-terminator ('\0').

, , :

const char* ptr = findTheChar("hello", 'l');
if(ptr)
    cout << *ptr << endl; //prints l
else
    cout << "Character not found" << endl;

, , (, Wall Wextra)?

In function 'int main()':
21:9: warning: this 'if' clause does not guard... [-Wmisleading-indentation]
         if (*ptr == x[1])
         ^~
23:13: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'if'
             ptr++;
             ^~~

:

if (*ptr == x[1])
        cout << *ptr << endl; //returns e
        ptr++;
+3

char* , . ,

char* x = "Hallo";

x "H".

std::cout << *x << std::endl;

std:: cout char.

std::cout << x << std::endl;

you have a special case where the output statement std :: ostream interprets char*as a pointer to a C-like string that ends with zero. Thus, x points to a single char, but the ostream operator for char*interprets this as a pointer to the first character of the string.

+2
source

Return * str and change the type of the returned function. This should work fine.

0
source

Source: https://habr.com/ru/post/1689937/


All Articles