Thomas
Thomas

Reputation: 1123

How to set pointer reference through a function

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.

Upvotes: 16

Views: 21148

Answers (4)

ant2009
ant2009

Reputation: 22556

I did it this way by returning the pointer from the function. There is no reason to use malloc in this case, so you don't have to worry about freeing.

gcc 4.4.3 c89

char* print_test(char *str)
{
    char *new_str =  "new_test";
    printf("new_str [ %s ]\n", new_str);
    str = new_str;
    return str;
}

int main(void)
{
    char *str = "test";

    printf("str [ %s ]\n", str);

    str = print_test(str);

    printf("str [ %s ]\n", str);

    return 0;
}

Upvotes: 0

Dummy00001
Dummy00001

Reputation: 17420

You need to use pointer to the pointer, untested:

#include <stdio.h>

void foo(char** str)
{
    char* new_str = malloc(100);
    memset(new_str, 0, 100);
    strcpy(new_str, (char*)"new test");
    if (str) { /* if pointer to pointer is valid then */
        if (*str)   /* if there is a previous string, free it */
            free(*str);
        *str = new_str;  /* return the string */
    }
}


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

Upvotes: 4

Eiko
Eiko

Reputation: 25632

You are just reassigning a pointer, which is a local variable in foo.

If you want to copy the string, use strcpy(str, new_str);

You could pass a reference to the pointer instead and reassign, but this can easily lead to memory leaks and is hard to maintain.

Edit: For the pseudo pass by reference see the answer by Steve.

Upvotes: 2

Steve Jessop
Steve Jessop

Reputation: 279305

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.

Upvotes: 29

Related Questions