[英]Change pointer's value in function
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: 当我用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)
Can anyone help me? 谁能帮我? I'm new in C.... 我是C新手。
Use a pointer to a pointer: 使用指向指针的指针:
void change(char **buf)
{
*buf = "xxxxxxx";
}
int main(void)
{
char *xxx = NULL;
change(&xxx);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.