I'm trying to return the data pointer from the function parameter:
bool dosomething(char *data){
int datasize = 100;
data = (char *)malloc(datasize);
// here data address = 10968998
return 1;
}
but when I call the function in the following way, the data address changes to zero:
char *data = NULL;
if(dosomething(data)){
// here data address = 0 ! (should be 10968998)
}
What am I doing wrong?
Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.
Passing Pointers to Functions in C++ C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.
Example 2: Passing Pointers to Functions Here, the value stored at p , *p , is 10 initially. We then passed the pointer p to the addOne() function. The ptr pointer gets this address in the addOne() function. Inside the function, we increased the value stored at ptr by 1 using (*ptr)++; .
You're passing by value. dosomething
modifies its local copy of data
- the caller will never see that.
Use this:
bool dosomething(char **data){
int datasize = 100;
*data = (char *)malloc(datasize);
return 1;
}
char *data = NULL;
if(dosomething(&data)){
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With