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?

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top