0

Can anybody point out why does the following code need char** pointer in the modify function. If i just pass char* and modify the value once the function call returns k has garbage value. Can somebody justify this?

char* call()
{
    return "fg";
}
void modify(char** i)
{
    *i = call();
}

int main()
{
    char* k= new char[3];
    modify(k);
}
2
  • 1
    How did this compile though ? modify takes a parameter of type char** and not char*. Also, use std::string instead. Commented Apr 9, 2012 at 17:38
  • Yes, please post code that actually compiles; otherwise it can be difficult to tell what you're asking about. Commented Apr 9, 2012 at 17:41

1 Answer 1

5

When you pass something into a function, you pass it by value. This means that the function operates on a copy of that thing.

This applies to pointers too. If you pass a char *, then a copy of that pointer gets made; the original pointer is not modified. If you want to modify the original pointer itself, then you need to pass its address, via a char ** argument.


Notes:

1. It's also worth pointing out that your code contains a memory leak. You dynamically-allocate some memory, and then lose the pointer to it, which means that you can never delete it.

2. In C++, you should generally avoid passing raw pointers around like this, because it causes pain and confusion. You should look into smart pointers.

Sign up to request clarification or add additional context in comments.

3 Comments

Worth noting that in C++ it generally gives more readable code to pass a reference to a pointer instead of a pointer to a pointer - but in C thats not an option.
More readable code yes. The declaration can be fun though. Let's throw in a template...
What if i modify the "modify" function program to take a reference to a pointer and pass the address while calling..Will there be a memory leak still?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.