Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to understand how pointers work here. The findTheChar function searches through str for the character chr. If the chr is found, it returns a pointer into str where the character was first found, otherwise nullptr (not found). My question is why does the function print out "llo" instead of "l"? while the code I wrote in main return an "e" instead of "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
}
like image 638
BnE Avatar asked Dec 10 '22 08:12

BnE


1 Answers

A C-string is a character buffer that is terminated by a '\0' character. Passing them around involves just passing a pointer to the first element.

All the library routines know that they may read characters starting at the address they are given, until they reach '\0'. Since that's how operator<< for std::cout is designed, it assumes you pass it the starting address of a C-string. That's the contract.

If you want to print a single character, you'll need to dereference that pointer.

like image 185
StoryTeller - Unslander Monica Avatar answered Feb 24 '23 15:02

StoryTeller - Unslander Monica