Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set pointer reference through a function

Tags:

c

In C, I am trying to set a pointer's value by sending it to a function, but the value wont change outside of the function. Here is my code:

#include <stdio.h>
void foo(char* str) {

    char* new_str = malloc(100);
    memset(new_str, 0, 100);
    strcpy(new_str, (char*)"new test");

    str = new_str;
}


int main (int argc, char *argv[]) {

    char* str = malloc(100);
    memset(str, 0, 100);

    strcpy(str, (char*)"test");

    foo(str);

    printf("str = %s\n", str);
}  

I want to print out:

str = new test 

but this code prints out:

str = test

Any help will be appreciated. Thanks in advance.

like image 873
Thomas Avatar asked Aug 19 '10 21:08

Thomas


1 Answers

There is no pass-by-reference in C. If you provide str as the argument to a function in C, you are always passing the current value of str, never str itself.

You could pass a pointer to str into the function:

void foo(char** pstr) {
    // ...
    *pstr = new_str;
}

int main() {
    // ...
    foo(&str);
}

As Eiko says, your example code leaks the first memory allocation. You're no longer using it, and you no longer have a pointer to it, so you can't free it. This is bad.

like image 52
Steve Jessop Avatar answered Nov 04 '22 18:11

Steve Jessop