0

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?

yunhasnawa
  • 815
  • 1
  • 14
  • 30
  • Looks more like C than C++ (the problem is that you're returning a pointer to a local variable which undefined behavior) – Pubby Dec 22 '12 at 15:08
  • What make it more like C than C++? Is it because i use char* rather than std::string? – yunhasnawa Dec 22 '12 at 15:16
  • Yes. Ideally you should use `std::string`, but since you're learning it's okay to use `char*`. You should also use things like `std::copy` instead of that `for` loop. – Pubby Dec 22 '12 at 15:20
  • Oh, I see. Thank you very much for your advice Sir. It took so much time for me to figure out what is exactly this char sequence things. – yunhasnawa Dec 22 '12 at 15:24

1 Answers1

4

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 *.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Rather than `malloc`, just pass a pointer to a string buffer which you will write into. – Pubby Dec 22 '12 at 15:11
  • Thanks. But is it better to use std::string than char sequence? What will you recommend me to use? Char sequence or std::string? I really need advice about this. – yunhasnawa Dec 22 '12 at 15:19
  • @yunhasnawa: Use `std::string`, it saves you all the problems of manual memory management which come with using `char *` and provides u everything that a `char *` provides u. – Alok Save Dec 22 '12 at 15:21