[英]C - assigning a value to a null pointer
Hi guys I'm new to C and pointers so I hope you'll forgive me. 嗨,大家好,我是C和指针的新手,希望您能原谅我。
I have the following code: 我有以下代码:
char *str = NULL;
*str = 'a';
printf("My string is :%s\n",str);
It compiles but I'm getting a segmentation error everytime. 它可以编译,但每次都会出现细分错误。 What is the cause of this and what how can I change it so that I can assign 'a' to my string? 这是什么原因造成的,如何更改它以便可以为字符串分配“ a”?
Thanks in advance! 提前致谢!
char *str = NULL;
The pointer str is not allocated yet. 指针str尚未分配。 So you can not dereference it. 因此,您不能取消引用它。 Then you tried to deference by 然后,您尝试遵从
*str = 'a';
The segmentation fault will occur. 分割错误将会发生。
If you want str with "a" value, you can do this way: 如果您希望str带有“ a”值,则可以执行以下操作:
char *str = "a";
printf("My string is :%s\n",str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.