在C语言中,字符串是通过在字符序列的末尾添加一个空字符(‘\0’)来终止的。

huangapple go评论67阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月16日 16:10:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定