Change pointer's value in function

早过忘川 提交于 2019-12-20 06:19:29

问题


I want to change the variable's value in the function. my code is like this:

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

when I debug with valgrind, it says:

==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)

Can anyone help me? I'm new in C....


回答1:


Use a pointer to a pointer:

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

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


来源:https://stackoverflow.com/questions/12451176/change-pointers-value-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!