簡體   English   中英

警告:格式'%c'需要類型'int',但參數2的類型為'char *'

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM