Question

I want to pass a cstring to a function and have it overwritten.

#include <stdio.h>

void changeStr(char* str1)
{
    str1 = "foo";
}

int main()
{
    char* aStr = "abc123";
    printf("%s\n", aStr);
    changeStr(aStr);
    printf("%s\n", aStr);//aStr is still the same :(
    return 0;
}

I tried putting a & in front of the aStr and * in front of str1 but then the program crashes. Why doesn't this work? Isn't the following the same reasoning as here?

Was it helpful?

Solution

You can do it this way:

#include <stdio.h>

void changeStr(const char** str1)
{
    *str1 = "foo";
}

int main()
{
    const char* aStr = "abc123";
    printf("%s\n", aStr);
    changeStr(&aStr);
    printf("%s\n", aStr);//aStr is still the same :(
    return 0;
}

here :

void changeStr(char* str1) {
    str1 = "foo";
}

str1 is a copy value that holds the address of "abc123", so any changes on it, it will be on the scope of the function. What you need is to modify the value of pointer itself, the holder of the address, so it points to "foo", that's why you need to pass char **, pointer to pointer.

OTHER TIPS

You need to use a pointer to pointer:

void changeStr(char** str1)
{
    *str1 = "foo";
}

int main()
{
    ...
    changeStr(&aStr);
    ...
}

In your original version the pointer is passed by value. When you change it to point to a different string, the change does not propagate back to the caller.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top