Reputation: 1179
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
?
Upvotes: 0
Views: 294
Reputation: 10539
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.
Upvotes: -2
Reputation: 42195
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();
Upvotes: 4
Reputation: 158599
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 *
.
Upvotes: 2