ASCII值= 0和'\ 0' [英] ASCII value = 0 and '\0'

查看:72
本文介绍了ASCII值= 0和'\ 0'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读这篇文章.但是当我尝试:

I have read this post. But when I tried:

  printf("before null %c after null\n", 0);  // (ASCII=0) != '\0' ??

而不是:

before null 

我得到了:

before null   after null

所以我的问题是:ASCII值0实际等于'\ 0'吗?

So my question is: Is ASCII value 0 actually equal to '\0'?

推荐答案

ASCII值0是否实际上等于 \ 0 ?

字符串在内存中的存储方式以及由诸如 printf()之类的函数处理的方式上的差异很重要.

The differences in how the strings are stored in memory and handled by functions like printf() are important.

"before null %c after null\n"
"before null \0 after null\n"

两者都存储在内存中,结尾处带有隐式 \ 0 终止符.第二个字符在中间有一个明确的 \ 0 字符,这一事实改变了事情.

Both are stored in memory with an implicit \0 terminator at the end. The fact that the second has an explicit \0 character in the middle changes things.

printf()将扫描字符串直到" end ",并在C中" end "中打印组件."通常表示直到第一个 \ 0 / nul 字符.

printf() will scan the string until "the end", printing components as it goes... in C "the end" typically means until the first \0 / nul character.

对于第一个变体, printf()将字符复制到输出中,直到到达%c 指令为止,此时它将查看给定的参数.函数...它可能会发现您给了'\ 0',或者它可能会发现您给了'+'-两种方式都将其复制到输出中.然后它将继续将字符复制到输出中,以查找字符串的"结尾".

With the first variant, printf() copies characters to the output until it reaches the %c directive, at which point it looks at the arguments that were given to the function... it might find that you gave '\0', or it might find that you gave '+' - either way, it copies this to the output. It'll then continue copying characters to the output, seeking "the end" of the string.

使用第二个变体, printf()将开始将字符复制到输出中,并找到"结尾"(由 \ 0 ),然后停止.

With the second variant, printf() will start copying characters to the output, will find "the end" (denoted by the \0), and stop.

如果要使用 snprintf(),则结果/输出将包含以下内容:(同样,使用隐式 \ 0 终止)

If you were to use snprintf(), then the results / outputs would contain the following: (again, with implicit \0 termination)

"before null \0 after null\n"
"before null "

如果随后要同时打印这两个文件,它们的外观会相同,但内存内容会有所不同.

If you were to subsequently print both of these, they would look the same, but the memory content would be different.

但是, printf()的输出是终端(或文件)... \ 0 的情况取决于终端仿真器...它可能根本不显示,可能显示为空格,或者可能带有有趣的框形符号...

However, the output of printf() is the terminal (or a file)... what happens for \0 depends on your terminal emulator... it might simply not be shown, it might be displayed as a space, or it may have a funny box symbol...

要注意的重要一点是,这发生在运行时-而不是编译时.

The important thing to note, is that this occurs at run time - not compile time.

这篇关于ASCII值= 0和'\ 0'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆