Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a pointer as a function parameter

Tags:

c++

c

pointers

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?

like image 731
Rookie Avatar asked Mar 12 '11 23:03

Rookie


People also ask

How do you pass a pointer to a function as a parameter?

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.

How do you pass a function pointer as a parameter in C++?

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.

How can we pass a pointer as an argument to a function explain with example?

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)++; .


1 Answers

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)){
}
like image 146
Erik Avatar answered Oct 04 '22 13:10

Erik