How do I return a pointer to something in the middle of a char array?
// Returns a pointer to the first occurrence of the given character in the
// given string.
const char* strchr(const char* string, char charToFind) {
for (int i = 0; i < strlen(string); i++) {
if (string[i] == charToFind) {
return string[i]; // <== THIS IS WRONG, How do I fix this?
}
}
return '\0';
}
You can do it like this
return &string[i];
or like this:
return string+i;
It's the same thing.
Returning '\0'
, a char
constant equal to zero, is logically incorrect: you should return 0
for a NULL
pointer, or if you wish to return an empty C string, you could return a pointer to local static empty string, like this:
const char* strchr(const char* string, char charToFind) {
for (int i = 0; i < strlen(string); i++) {
...
}
// Not found - return an empty string:
static const char *empty = "";
return empty;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments