Rookie
Rookie

Reputation: 1242

How to return a pointer as a function parameter

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?

Upvotes: 16

Views: 16660

Answers (2)

pmg
pmg

Reputation: 108986

int changeme(int foobar) {
  foobar = 42;
  return 0;
}

int  main(void) {
  int quux = 0;
  changeme(quux);
  /* what do you expect `quux` to have now? */
}

It's the same thing with your snippet.

C passes everything by value.

Upvotes: 2

Erik
Erik

Reputation: 91320

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)){
}

Upvotes: 29

Related Questions