我们怎样才能写出这种类型的语法
#include<stdio.h>
main()
{
char *str;
str="%s";
printf(str,"K\n");
return 0;
}
printf
声明有效吗?
Yes, it is valid, since your str
is of type char *
. This is the prototype of printf:
int printf ( const char * format, ... );
From the view of the called function, your statement will be the same as:
printf("%s","K\n");
With "%s"
and "K\n"
being a constant expressions of the type char *
.
函数调用printf()
是有效的,因为作为它的第一个参数,它需要一个常量字符串作为格式说明符。不要认为字符串是放在引号之间的东西 - 将其视为字符数组(加上终止的 0 字符)。在 C(以及任何有意义的编程语言)中,只要有一个值,它的类型和实际值/内容就决定了它的行为 - 让它成为文字、变量或任何其他表达式(我们暂时不考虑 const 的正确性为了简单起见)。就像在数学中一样,你是否写作并不重要
3 + 2 = 5
或者
x = 3
y = 2
x + y = 5
尽管 x 和 y 不是文字,但第二个相等的第三行仍然有效。它们是变量,在使用它们时会使用它们的当前值。
现在关于 const 正确性的一个小问题是其他答案所缺乏的:字符串文字是类型的const char *
,而不是char *
因为你不能改变它的内容。所以写起来不太好
char *foo = "blah blah";
改写
const char *foo = "blah blah";
Yes, the syntax is valid. The result of this program is the string "K\n"
Where \n means newline.
The %s tells printf that the first arg it will be printing should be printed as a string.
See this: http://www.cplusplus.com/reference/clibrary/cstdio/printf/
This is a very simple program. In the time it took you to ask this question, you could have compiled and run the program yourself and seen the answer. You learn best by doing.
printf("%s","K\n");
- 此语句两个字符串文字%s
ans k\n
。这两个字符串文字将在文本段中作为只读数据。现在考虑1000
的是字符串文字的地址,%s
并且2000
是字符串文字的地址k\n
。1000
并且2000
将是两个争论,这将传递给printf
.
printf("%s","K\n");
这也可以写成下面的方式
...
char *a = "%s"; //Address 1000 is stored in a
char *b = "k\n"; //Address 2000 is stored in b
printf(a,b); //Now we are passing 1000 and 2000 to printf
...
而且我想告诉你,下面的方法也可以打印一个字符串。
...
char *a = "hello world"
printf(a); //This will print hello world
...