我想更改函数中变量的值。
我的代码是这样的:

void change(char *buf){
    char str = "xxxxxxx";
    *buf = &str;
}
int main(){
    char *xxx = NULL;
    change(xxx);
}

当我用valgrind调试时,它会说:
==3709== Invalid write of size 1
==3709==    at 0x80483CA: change (test.c:5)
==3709==    by 0x80483E5: main (test.c:10)
==3709==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==3709==
==3709==
==3709== Process terminating with default action of signal 11 (SIGSEGV)
==3709==  Access not within mapped region at address 0x0
==3709==    at 0x80483CA: change (test.c:5)
==3709==    by 0x80483E5: main (test.c:10)

有人能帮我吗?我是新来的。。。。

最佳答案

使用指向指针的指针:

void change(char **buf)
{
    *buf = "xxxxxxx";
}

int main(void)
{
    char *xxx = NULL;
    change(&xxx);
}

关于c - 在函数中更改指针的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12451176/

10-12 02:13