Have one question and one issue:
The question- I have to write a function of type pointer to char that returns a pointer when it finds a match.
(This is the actual exercise question):
Write a function that returns a pointer to the first occurrence of the character c in the string s, or nullptr if there is no match.
char* find(char s[], char c) (Horstmann, 2017-08-12,
#include <iostream>
#include <cstring>
usingnamespace std;
char* find(char s[], char c)
{
int size = strlen(s);
char* p = nullptr;
for (int i = 0; i < size; i++)
{
if (s[i] == c)
{
return p = s + i;
}
}
return p;
}
int main()
{
char word[] = "James";
cout << find(word, 'm');
return 0;
}
So is this what they are asking for? I thought by "returning a pointer" they were asking for the address of the character that is matched. But it seems that it returns the characters starting with that match. Is this because its a type char so thus giving the address as type char?
The issue i have is with the nullptr. when i return it i get an error. I'm assuming that it has to do with the return type being a pointer to type char?
specifically for c-strings you could also return the pointer to the 0 end of string marker character.
then its just
if(*ch) //the POINTER is valid, the CHARACTER POINTED TO is 'outside' the string and special
//found
else //not found
and avoid the entire aggravation with nullptrs.
to do this, in the above find() code, return s instead of nullptr. the loop condition already ensures that s was the end of string marker... so its ready to go.