0
void funcF(char *outBuffer)
{
        char * inBuffer;
        inBuffer = (char *) malloc(500);
        // add stuff to inBuffer
        strcpy(inBuffer, "blabla");

        outBuffer = inBuffer; //probably this is wrong 
}

int main()
{
    char * outBuffer;

    funcF(outBuffer);

    printf("%s", outBuffer); // i want to get "blabla" as output
    free(outBuffer);
}

My question how can i make outBuffer point to the same address as inBuffer so that i can access the data in inBuffer ?

3 Answers 3

4

Your current code passes a pointer by value. This means that funcF operates on a copy of the caller's pointer. If you want to modify the caller's pointer, you need to either pass the address of that pointer (i.e. a pointer to a pointer):

void funcF(char **outBuffer)
{
    char * inBuffer = malloc(500);
    strcpy(inBuffer, "blabla");
    *outBuffer = inBuffer;
}

int main()
{
    char * outBuffer;
    funcF(&outBuffer);
    //    ^

or change funcF to return a pointer:

char* funcF()
{
    char* inBuffer = malloc(500);
    strcpy(inBuffer, "blabla");
    return inBuffer;
}

int main()
{
    char * outBuffer = funcF();
Sign up to request clarification or add additional context in comments.

Comments

2

You need to pass a char **:

void funcF(char **outBuffer)

then assign like this:

*outBuffer = inBuffer;

and pass it in like so:

funcF(&outBuffer);

you can alternatively, have it return a char *.

Comments

-2

Not sure if this is what you want, but:

int main() {

const unsigned int MAX_BUFF = 1024

char outBuffer[MAX_BUFF];

funcF(outBuffer);

printf("%s", outBuffer); // i want to get "blabla" as output

/* free(outBuffer); */

}

will have problem with free(), but you get the idea.

2 Comments

This doesn't seem to answer the question. The questioner is asking about getting a pointer back from a called function, but your answer is about not getting a pointer back from the called function.
Sure, I noticed that. In the way I suggest the (hidden) pointer is send to the called function - opposite to what was asked.

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.