简体   繁体   English

谁能解释一下这段代码的输出?

[英]Can anyone explain me the output of this code?

char c[] = "hello"; 

printf("%*d", c);

the output is :输出是:

infinite loop of spaces空间无限循环

在此处输入图片说明

Can anyone explain me the output of this code?谁能解释一下这段代码的输出?

infinite loop of spaces空间无限循环

char c[] = "hello";

printf("%*d", c);

the %*d say the first arg after the format indicates the width, here it is the address of c interpreted as a huge number, and the default added character to respect the width is a space. %*d表示格式后的第一个 arg 表示宽度,这里是c的地址解释为一个巨大的数字,默认添加的尊重宽度的字符是一个空格。

note there is a missing arg normaly giving the value to print请注意,通常缺少 arg 给出要打印的值


if I use a valid code like that :如果我使用这样的有效代码:

#include <stdio.h>

int main()
{
  printf("%0*d\n", 3, 1);
  return 0;
}

the result is 001 because I ask for to write '1' with a width of 3 and the added character is '0'结果是 001 因为我要求写宽度为 3 的 '1' 并且添加的字符是 '0'

first we understand what is c[]="hello";首先我们了解什么是 c[]="hello"; c is an array of char which holds hello but what is array array is pointer with chunk of memory mean above we create a array means we create a pointer whose point hello blocks memory like c means c contain adresse of first block of hello but what happened in printf("% d",c) asterisk( ) symbol represent width then first argument is width like this printf("%*c",3,c): its output is give : h here is width three and print a char which hold c :now see why screen has infinite loop let's see printf("%*d",c) as we know first argument is width of output here is a char c mean bas adress when Code executed it give adress to width and u know adress is too long and it sometime negative then why your screen have too much space not infinite because u give width as a long as a adress further doubt comment me c 是一个包含 hello 的 char 数组,但什么是数组数组是带有内存块的指针,上面的意思是我们创建一个数组意味着我们创建一个指针,其点 hello 阻塞内存,如 c 意味着 c 包含第一个 hello 块的地址,但是发生了什么在 printf("% d",c) 星号( ) 符号代表宽度然后第一个参数是宽度,像这样 printf("%*c",3,c): 它的输出是: h 这里是宽度三并打印一个字符其中包含 c :现在看看为什么屏幕有无限循环让我们看看 printf("%*d",c) 因为我们知道第一个参数是输出宽度这里是一个字符 c 意思是代码执行时的基本地址,它给出了宽度和 u 的地址知道地址太长,有时是负面的,那么为什么你的屏幕有太多的空间而不是无限的,因为你给出的宽度与地址一样长,进一步怀疑评论我

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

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