putc函数的用法
我正在编写一个不是我编写的 C 程序,并将其与我的 C++ 代码集成。这个C程序有一个字符数组并使用putc函数来打印它的内容。像这样:
printf("%c\n","01"[b[i]]);
这是一个位数组,可以有 ASCII 0 或 ASCII 1(不是 ASCII 48 和 49,请注意)。该命令完美地打印“0”和“1”。但是,我不明白putc命令中“01”的用法。我还可以打印这样的内容:
printf("%d\n",b[i]);
因此我只是好奇。谢谢。
新手
I am working on a C program that I did not write and integrating it with my C++ code. This C program has a character array and usage putc function to print the content of it. Like this:
printf("%c\n","01"[b[i]]);
This is a bit array and can have either ASCII 0 or ASCII 1 (NOT ASCII 48 and 49 PLEASE NOTE). This command prints "0" and "1" perfectly. However, I did not understand the use of "01" in the putc command. I can also print the contents like this:
printf("%d\n",b[i]);
Hence I was just curious. Thanks.
Newbie
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
"01"
是一个字符串文字,实际上它是一个数组。看起来有点奇怪......你可以写:或者甚至更好:
乍一看会更容易理解。
The
"01"
is a string literal, which for all intents and purposes is an array. It's a bit weird-looking... you could write:or maybe even better:
And it would be a little easier to understand at first glance.
做这项工作的方式很糟糕,但无论谁写这个都是使用 b 的内容作为字符串“01”的数组取消引用:
你的数组 b 包含 0 和 1,作者想要一种方法来快速将它们转换为“0”和“1”。他可以,而且很容易做到:
但那是另一种犯罪行为。 =]
Nasty way of doing the work, but whoever wrote this was using the contents of b as an array dereference into the string, "01":
your array, b, contains 0s and 1s, and the author wanted a way to quickly turn those into '0's and '1's. He could, just as easily have done:
But that's another criminal behavior. =]
字符串“01”被转换为字符数组(这就是 C 中的字符串),并且 b[i] 指定 0 或 1,因此它的“分解”视图就是这样。
或
将从字符数组“字符串”中选择“正确”的字符。请注意,由于字符串是指向字符的指针的定义,这仅适用于 C。因此,[...]操作变成了一种内存偏移操作,其大小等于指针类型的一项(在本例中为一个字符)的大小。
是的,你的 printf 会好得多,因为它需要更少的晦涩的“c”技巧知识。
The String "01" is getting cast into a character array (which is what strings are in C), and the b[i] specifies either a 0 or a 1, so the "decomposed" view of it would be.
or
Which would select the "right" character from the char array "string". Note that this is only possible C due to the definition that a string is a pointer to a character. Thus, the [...] operation becomes a memory offset operation equal to the size of one item of the type of pointer (in this case, one char).
Yes, your printf would be much better, as it requires less knowledge of obscure "c" tricks.
这行代码表示获取字符数组
"01"
并引用数组元素。从 b[i] 位置获取该索引。因此,
"01"[0]
返回字符0
,"01"[1]
返回字符1
This line is saying take the array of characters
"01"
and reference an array element. Get that index from the b[i] location.Thus
"01"[0]
returns the character0
and"01"[1]
returns the character1
做你理解的陈述。
简化另一个,通过将
b[i]
替换为索引,我们得到字符串文字 (
"01"
) 的类型为char[3].获取其索引
0
或1
(或2
)即可,并返回字符'0'
或'1'
(或'\0'
)。Do the statement you understand.
Simplifying the other one, by replacing
b[i]
with index, we getThe string literal (
"01"
) is of typechar[3]
. Getting its index0
or1
(or2
) is ok and returns the character'0'
or'1'
(or'\0'
).