C语言 打印字符 *
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15284473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing a Char *
提问by Alex Nichols
I apologize in advance for the dumb question!
对于这个愚蠢的问题,我提前道歉!
Here is my struct def:
这是我的结构定义:
struct vcard {
char *cnet;
char *email;
char *fname;
char *lname;
char *tel;
};
I am trying to print a representation of this struct with the function vcard_show(vcard *c), but the compiler is throwing back an warning:
我正在尝试使用函数 vcard_show(vcard *c) 打印此结构的表示,但编译器正在抛出警告:
void vcard_show(struct vcard *c)
{
printf("First Name: %c\n", c->fname);
printf("Last Name: %c\n", c->lname);
printf("CNet ID: %c\n", c->cnet);
printf("Email: %c\n", c->email);
printf("Phone Number: %c\n", c->tel);
}
When compiled: "warning: format ‘%c' expects type ‘int', but argument 2 has type ‘char *'"
编译时:“警告:格式 '%c' 需要类型 'int',但参数 2 的类型为 'char *'”
Isn't %c the symbol for char*?
%c 不是 char* 的符号吗?
回答by Jonathon Simister
You want to use %s, which is for strings (char*). %cis for single characters (char).
您想使用%s, 用于字符串 (char*)。%c用于单个字符(char)。
An asterisk *after a type makes it a pointer to type. So char*is actually a pointer to a character. In C, strings are passed-by-reference by passing the pointer to the first character of the string. The end of the string is determined by setting the byte after the last character of the string to NULL (0).
*类型后的星号使其成为指向类型的指针。所以char*实际上是一个指向字符的指针。在 C 中,字符串通过将指针传递到字符串的第一个字符来按引用传递。字符串的结尾是通过将字符串的最后一个字符之后的字节设置为 NULL (0) 来确定的。
回答by DanZimm
The property type encoding for a char *is %s. %cis for a char(not the pointer just a single char)
a 的属性类型编码char *是%s. %c是一个char(不是指针只是一个char)
回答by Crash Magnet
Unless you have some typedef you are not telling us about, you should probably declare vcard_show()like this:
除非你有一些 typedef 你没有告诉我们,你应该vcard_show()像这样声明:
void vcard_show(struct vcard *c)

