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
}
cout << findTheChar("hello", 'l') << endl; //returns llo
Return type of findTheChar
is const char *
. When you try to print a const char *
with std::cout
it would print the character array pointed by the address upto terminating \0
character.
str -> +---+---+---+---+---+---+
| h | e | l | l | o | \0|
+---+---+---+---+---+---+
^
|
findTheChar(str, 'l')
If you want just one character, dereference the address (If it is not null). If you want to print the return address, you can typecast it to void *
.
while the code i wrote in main return an "e" instead of "ello"
cout << *ptr << endl; //returns e
Here you are explicitly dereferencing the ptr
as *ptr
and thus you are printing a char
and not const char *
.
As you are using C++, you would be better with std::string
and iterators.
// Returns offset of first occurance if found
// Returns -1 if not found
int findTheChar(const std::string& str, char chr );