Question

Just start learning C++ and trying to make a simple function that do substring with following code:

char* substring(int start, int end, const char* target)
{
    size_t length = strlen(target);

    char result[(length + 1)];

    int iterator = 0;

    for(int i = start; i < length; i++)
    {
        if(i <= end)
        {
            result[iterator] = target[i];

            iterator++;
        }
    }

    result[iterator] = '\0';

    cout << result << endl; // This give correct result "aya";

    return result;
}

When I use these function on main method:

int main(int argc, char** argv) {

    char some_text[] = "Saya Makan";

    char* sub = substring(1, 3, some_text); // No string returned

    cout << "Substring Result is: " << sub;

    return 0;
}

It give output is like this:

aya
Substring Result is: 
RUN SUCCESSFUL (total time: 44ms)

As seen on the result, my function isn't returning anything but empty string although a line of code before return, the "result" variable echoed result correctly. Would you please explain to me what is happening inside my function, am I missing something?

Was it helpful?

Solution

You are returning pointer to a local array which is not required to live beyond the function.

You need to make the buffer persist beyond the scope of the function by allocating it dynamically using malloc. And ofcourse remember to free it later.

Oh just noticed its C++.
So drop the idea of malloc and free simply use std::string and not char *.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top