[英]What will be the output of the following program written in C?
I am a novice for C language.but I could understand why this following code is giving output as 'A' . 我是C语言的新手,但我能理解为什么下面的代码将输出显示为'A' 。
one thing that is bothering me is the array name p in the printf statement.how this p is being treated by the compiler? 让我困扰的一件事是printf语句中的数组名称p。编译器如何处理该p?
How can the p is replaced by the character array "%c\\n" after line no 5 ? 在第5行之后,如何用字符数组“%c \\ n”替换p ?
I know that this is a silly question so sorry to post this hare. 我知道这是一个愚蠢的问题,非常抱歉发布此兔子。
Can anyone will help me to understand the concept behind this? 谁能帮助我理解其背后的概念?
line1: #include<stdio.h>
line2: int main()
line3: {
line4: char p[]="%d\n";
line5: p[1]='c';
line6: printf(p,65);
line7: return 0;
}
The first argument to printf()
is a const char*
that contains the format specifiers. printf()
的第一个参数是const char*
,其中包含格式说明符。 It is more common to see it as a string literal: 更常见的是将其视为字符串文字:
printf("%c\n", 65);
but it is legal to use a variable containing a string. 但是使用包含字符串的变量是合法的。
The assignment of p[1] = 'c'
changes the d
to c
in the buffer p
, resulting in the character A
(as 65
is decimal value for A
) being written to standard output (as %c
instructs printf()
to print the character, rather than %d
which will print the numeric value). 的分配
p[1] = 'c'
的改变d
,以c
在缓冲器p
,导致字符A
(如65
为十进制值A
)被写入到标准输出(作为%c
指示printf()
打印字符,而不是%d
将打印数字值)。
You are not replacing the whole array, just the character at array's offset #1 (second character). 您不会替换整个数组,而只是替换数组偏移量为#1的字符(第二个字符)。 you are replacing it with 'c' making the content to be "%c\\n" which, when used as a formatting string, formats the integer 65 as an upper-case Latin A
您将其替换为“ c”,使内容变为“%c \\ n”,当用作格式字符串时,将整数65格式化为大写拉丁字母A
In line 6: 在第6行中:
printf(p,65);
will be changed to 将更改为
printf("%c\\n",65);
Ascii Value of 'A' is 65. “ A”的Ascii值为65。
http://www.asciitable.com/ http://www.asciitable.com/
Explanation below: 解释如下:
char p[]="%d\n";
After the above executes, P will contain -> "%d\\n" 执行完上述操作后,P将包含->“%d \\ n”
line5: p[1]='c';
Here, P will now be "%c\\n", as you are changing the 1th character of a zero based indexing. 在这里,当您更改基于零的索引的第一个字符时,P现在将为“%c \\ n”。
line6: printf(p,65);
This is equivalent to: 这等效于:
printf("%c\n",65)
or 要么
printf("%c\n",'A')
Hence you get the output of A 因此,您得到A的输出
#include<stdio.h>
int main()
{
char p[]="%d\n"; #This is stored at p[1]
p[1]='c' # d is replaced by c
printf(p,65); # p is taken as p[1] and is replaced by "%c\n"
return 0;
}
output: A # ASCII value 65 输出:A#ASCII值65
If you give the value as 66 output will be 'B" and so on. 如果将值设置为66,则输出将为“ B”,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.