[英]When do i have to add a null terminator?
I know that i C , you always have to add a null terminator \\0
so that the processor knows when a word was ended . 我知道我C,您总是必须添加一个空终止符
\\0
以便处理器知道单词何时结束。
But i get hard time to understand when you have to do it . 但是我很难理解你什么时候要做。 so for example this code works for me without it :
因此,例如,这段代码在没有它的情况下对我有效:
char connectcmd[50]={0};
sprintf(connectcmd,"AT+CWJAP=\"%s\",\"%s\"",MYSSID,MYPASS);
How is that possible ? 那怎么可能呢? When do you really have to add them ?
您何时真正需要添加它们?
sprintf
always terminates it with null character
, so no need to mannually add it. sprintf
总是以null character
终止它,因此无需手动添加它。
From C99 standard - 从C99标准-
7.21.6.6 The sprintf function
7.21.6.6 sprintf函数
[...]A null character is written at the end of the characters written;
[...]在写入的字符的末尾写入一个空字符; it is not counted as part of the returned value.
它不算作返回值的一部分。 If copying takes place between objects that overlap, the behavior is undefined.
如果在重叠的对象之间进行复制,则行为是不确定的。
for example this code works for me without it
例如,没有它,此代码对我有用
It does not (work without it). 它不能( 没有它就可以工作)。
The string literal "AT+CWJAP=\\"%s\\",\\"%s\\""
has a null terminator at the end (like every string literal). 字符串文字
"AT+CWJAP=\\"%s\\",\\"%s\\""
在结尾处有一个空终止符(就像每个字符串文字一样)。 sprintf
copies that null terminator to connectcmd
as well. sprintf
connectcmd
空终止符也复制到connectcmd
。
When do you really have to add them ?
您何时真正需要添加它们?
When you're manually building a string, or using a library function whose documentation explicitly states that it isn't going to add a terminating null. 当您手动构建字符串或使用库函数(其文档中明确指出不会添加终止null)时。
sprintf
writes a null terminated string connectcmd
, regardless of its initial contents. sprintf
写入一个以null结尾的字符串connectcmd
,而不管其初始内容如何。 This works as long as you don't try to write beyond the bounds of the buffer. 只要您不尝试写超出缓冲区范围的代码,此方法就起作用。
On top of that, when you say this: 最重要的是,当您这样说:
char connectcmd[50]={0};
you initialize all 50 elements of connectcmd
to zero, which is the value of the null-terminator \\0
. 您将
connectcmd
所有50个元素初始化为零,这是空终止符\\0
。 So it would be null-terminated even if you wrote characters to it manually, as long as you write less than 50
non-null characters. 因此,即使您手动写入字符,只要您写入的字符少于
50
,它也将以null终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.