0

関数に cstring を渡して上書きしたい。

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

&aStr の前と str1 の前に a を配置しようと*しましたが、プログラムがクラッシュします。なぜこれが機能しないのですか?以下は、ここと同じ理屈ではないでしょうか?

4

2 に答える 2

2

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.

于 2013-11-01T22:32:27.030 に答える
2

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.

于 2013-11-01T22:32:37.033 に答える