[英]warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
[英]warning: format '%c' expects type 'int', but argument 2 has type 'char *'
我正在嘗試將以十六進制數組存儲的所有字符逐個打印到屏幕上,但我在第16行中得到了這個奇怪的錯誤。據我所知,%c應該期待一個字符,而不是一個int。 為什么我收到此錯誤? 下面是我的代碼,謝謝。
#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;
}
你的意思是
printf("%c", *currentHex);
在我看來,你可以刪除currentHex
的整個想法,因為它只是增加了沒有價值的復雜性。 簡單地說:
printf("%c", hex[hexCounter]);
重要的一點是,你應該傳遞角色本身的價值 ,而不是你正在做的地址。
你有hex[hexCounter]
作為char
所以當你設置
currentHex = &hex[hexCounter];
您將currentHex
設置為char
的地址,即char *
。 因此,在您的printf
您需要
printf("%c",*currentHex);
無論如何,你所做的事情是不必要的,因為你可以做到
printf("%c",hex[hexCounter]);
currentHex
應該是char
類型,而不是char *
。
char currentHex;
[..]
currentHex = hex[hexCounter];
printf("%c",currentHex);
如果你真的希望它是一個指針,請取消引用它來打印:
printf("%c",*currentHex);
這是修改后的代碼,對我運行正常 -
#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.