字符串终止符"\ 0"如何与整数常量0具有相同的值? [英] How is the string terminator '\0' has the same value as integer constant 0?
问题描述
我有以下代码-
#include <stdio.h>
#define LENGTH 5
int main(){
char* ch[LENGTH] = {"Zero", "One", "Two", "Three", "Four"};
char* pc;
char** ppc;
for(int i=0; i<LENGTH; i++){
ppc = ch+i;
pc = *ppc;
while(*pc != 0){
printf("%c ", *pc);
pc = pc +1;
}
printf("\n");
}
return 0;
}
这是使用字符串进行多次间接访问的示例.
It is an example of multiple indirection using string.
输出为
Z e r o
O n e
T w o
T h r e e
F o u r
在while()
循环中而不是*pc != '\0'
,而是使用*pc != 0
.
Here in while()
loop instead of *pc != '\0'
, *pc != 0
is used.
但是两种方法都给出相同的输出.为什么会这样呢?
But both the approaches give same output. Why is it so?
推荐答案
换行符\n
,制表符\t
等具有其自己的转义序列字符,但实际上不存在用于空终止符的字符.
Line feed \n
, tab \t
etc has their own escape sequence characters, but actually there does not exist one for the null terminator.
因此,重新表示空终止符的行业事实上的标准方法是编写一个值为零的八进制转义序列.八进制转义序列定义为\
,后跟数字.所以\0
只是表示零,以八进制表示.由于这看起来与其他字符转义序列相似,因此它已成为表示空终止符的事实上的标准方法.
The industry de facto standard way of represending the null terminator is therefore to write an octal escape sequence with the value zero. Octal escape sequences are defined as \
followed by a number. So \0
simply means zero, with octal representation. Since this looks similar to other character escape sequences, it has become the de facto standard way of representing the null terminator.
这就是为什么十进制0
可以一样好地工作的原因,它是将值写入零的另一种方式.如果您想晦涩难懂,也可以写\x0
.
This is why a decimal 0
works just as fine, it is just another way of writing the value zero. You could as well write \x0
if you wish to be obscure.
这篇关于字符串终止符"\ 0"如何与整数常量0具有相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!