英文:
How does a String terminate in C?
问题
我知道在C语言中,字符串会以字符\0
结尾。
然而,如果我这样做:char a[5]="abcd\n"
,那么\0
会在哪里呢?
或者,无论何时我尝试使用char[]
来存储一个字符串,我是否需要至少保留一个位置来存放\0
?
谢谢你的帮助!
英文:
I know the string in c will be terminated by a character \0
.
However, if I do char a[5]="abcd\n"
, where would \0
be?
Or do I need to reserve at least one position for \0
, whenever I try to use char[]
to store a string?
Thank you for any help!
答案1
得分: 3
只要不指定大小,让编译器确定缓冲区的大小即可。实际缓冲区大小将为6,以容纳您的5个字节和1个终止零字节。当您键入"something"而不进行赋值时,编译器将该字符串放在程序中的一个专用位置,最后一个字符后至少有1个零字节。
写
char a[5]="abcd\n"
是不好的做法,因为它会导致像strcpy()这样的函数以未定义的方式运行,因为您的变量 'a' 不是C字符串,而只是一个字符缓冲区,碰巧所有字符都是可打印/可见的,最后有一个终止符\n。
英文:
You should do:
char a[]="abcd\n";
without specifying the size to let compiler figure out the buffer size. The actual buffer will have size of 6 to accommodate your 5 bytes + 1 byte for terminating zero. When you type "something" without assignment, compilaer puts that string in a dedicated place in the program with at least 1 zero byte after the last character.
Writing
char a[5]="abcd\n"
is a bad practice because it will cause functions like strcpy() to act in undefined manner as your variable 'a' is not a c string, but just a buffer of characters, which by chance seem to be all printable/visible + terminating \n
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论