[英]warning: format '%c' expects type 'int', but argument 2 has type 'char *'
I'm trying to print all characters stored in hex array to the screen, one by one, but I get this strange error in line 16. As far as I know, %c should be expecting a char, not an int. 我正在尝试将以十六进制数组存储的所有字符逐个打印到屏幕上,但我在第16行中得到了这个奇怪的错误。据我所知,%c应该期待一个字符,而不是一个int。 Why I'm getting this error?
为什么我收到此错误? Below is my code, thanks.
下面是我的代码,谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <string.h>
int main()
{
char hex[8] = "cf0a441f";
int hexCounter;
char *currentHex;
for(hexCounter=0; hexCounter<strlen(hex); hexCounter++)
{
currentHex = &hex[hexCounter];
printf("%c",currentHex);
}
return 0;
}
You mean 你的意思是
printf("%c", *currentHex);
In my opinion you can remove the entire idea of currentHex
since it just adds complexity for no value. 在我看来,你可以删除
currentHex
的整个想法,因为它只是增加了没有价值的复杂性。 Simply do: 简单地说:
printf("%c", hex[hexCounter]);
The important point is that you're supposed to pass the value of the character itself, not it's address which is what you're doing. 重要的一点是,你应该传递角色本身的价值 ,而不是你正在做的地址。
You have hex[hexCounter]
as a char
so when you set 你有
hex[hexCounter]
作为char
所以当你设置
currentHex = &hex[hexCounter];
you are setting currentHex
to the address of a char
, ie a char *
. 您将
currentHex
设置为char
的地址,即char *
。 As such, in your printf
you need 因此,在您的
printf
您需要
printf("%c",*currentHex);
What you are doing is unnecessary anyway, since you could just do 无论如何,你所做的事情是不必要的,因为你可以做到
printf("%c",hex[hexCounter]);
currentHex
should be of type char
, not char *
. currentHex
应该是char
类型,而不是char *
。
char currentHex;
[..]
currentHex = hex[hexCounter];
printf("%c",currentHex);
If you really want it to be a pointer, dereference it to print: 如果你真的希望它是一个指针,请取消引用它来打印:
printf("%c",*currentHex);
Here's the modified code which runs fine for me - 这是修改后的代码,对我运行正常 -
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <string.h>
int main()
{
char hex[9] = "cf0a441f";
unsigned int hexCounter;
char *currentHex;
for(hexCounter=0; hexCounter<strlen(hex); hexCounter++)
{
currentHex = &hex[hexCounter];
printf("%c",*currentHex);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.