How do I return a pointer to something in the middle of a char array?

Wang-Zhao-Liu Q

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';
}
Sergey Kalinichenko

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.

edited at
0

Comments

0 comments
Login to comment

Related

How do I return the middle of a python array?

How do I correctly work with char pointer to array in C++?

How do I cast /copy from a char array so that I may store it in a char pointer array?

How do I return a char array of an unknown value?

How do I Display Something in the Exact Middle of the Display Screen?

How do I add an item to the middle of an array?

returning a pointer that points to char array. How do i print out the entire contents of the array?

What if the function would return a pointer to a char array and I would not use it

How can i put a char pointer into an array char in a for loop in {C}

How do I return a function pointer as const?

How do I return a character array from char *functionName(int arrayname[SIZE]);

How do i change the content of pointer array?

how do i pass an array with a pointer into a function?

How do I initialize a pointer to an Array of structure

How do I return an iterator that has a reference to something inside a RefCell?

How can I copy a string into a char array pointer?

How do I make an FFI call with a char** pointer?

How do I allocate memory to my char pointer?

How to split char pointer with multiple delimiters & return array of char pointers in c++?

how do I free this char** array?

How do I add String to a char array?

How do I insert char* to array of structures?

How do I use tolower() with a char array?

How do you return a char * two char pointer? Local variable is being returned error c++

how do I tell an array pointer from a regular pointer

How do I find the middle of a 2d array?

How do I shift a bash array at some index in the middle?

How do I put a specific integer into the middle of a sorted array in Swift?

how do I read an array and return an array?