简体   繁体   English

printf如何工作?

[英]How does printf work?

I looked over but couldn't find a decent answer. 我看了看但找不到合适的答案。

I was wondering how printf works in case like this: 我想知道printf是如何工作的,如下所示:

char arr[2] = {5,6};

printf ("%d%d",arr[0],arr[1]);

I was thinking that printf just walks through the format and when it encouter %d for example it reads 4 bytes from the it's current position... however that's gotta be misconcepition cause that above works perfectly. 我认为printf只是遍历格式,当它包含%d时,例如它从它的当前位置读取4个字节...但是这是错误的,因为上面的工作完美。

so, where am I wrong ? 那么,我哪里错了?

You're right. 你是对的。 But there's argument promotion that converts (among other things) your char :s into int :s when they are used with a "varargs" function like printf() . 但是有一个参数提升 ,它将你的char :s转换为int :s,当它们与printf()这样的“varargs”函数一起使用时。

When you say: 当你说:

 printf ("%d%d",arr[0],arr[1]);

the string and the result of evaluating the two array expressions are placed on the stack and printf is called. 字符串和评估两个数组表达式的结果放在堆栈上并调用printf printf takes the string from the stack and uses the % formatters in it to access the other stacked arguments in sequence. printf从堆栈中获取字符串,并使用其中的%formatters按顺序访问其他堆栈参数。 Exactly how it does that depends, as you say on the actual % value - for example, %d reads 4 bytes but %f reads 8 (for most 32-bit architectures). 具体如何取决于实际的%值 - 例如, %d读取4个字节,但%f读取8个(对于大多数32位体系结构)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM