简体   繁体   中英

C - assigning a value to a null pointer

Hi guys I'm new to C and pointers so I hope you'll forgive me.

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?

Thanks in advance!

char *str = NULL;

The pointer str is not allocated yet. 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:

char *str = "a";
printf("My string is :%s\n",str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM