为什么编译器会抱怨这个'sprintf`参数?

时间:2016-01-19 16:11:30

标签: c compiler-errors printf

以下代码用于编译罚款。我将项目迁移到新版本,现在编译器抱怨我的sprintf个参数之一。这是警告:

warning: format '%02d' expects type 'int', but argument 12 has type 'double'

仅供参考,IDE为MPLAB X 2.35,编译器为XC 1.34。我关闭了优化,我尝试了清理/构建。我只能怀疑结构对齐可能不合适。我希望我只是错过了明显的,比如无法计算。

违规代码:

typedef struct _AnalysisEvent
{
    unsigned short id;
    unsigned char day;
    unsigned char month;
    unsigned char year;
    unsigned char hour;
    unsigned char minute;
    unsigned char second;
    unsigned int duration;
    double min;
    double max;
    double avg;
} AnalysisEvent;

AnalysisEvent AnalysisEvents[ANALYSIS_MAX_COUNT][ANALYSIS_EVENTS_MAX_COUNT];

unsigned char AnalysisEventGetValueStrAlt(unsigned short id, unsigned char index, char *buffer, int length)
{
    if (Analysis[id].count > index)
    {
        sprintf(buffer, "Analysis ID: %d\r\nEvent ID: %d\r\nMin: %.2f\r\nMax: %.2f\r\nAvg: %.2f\r\nTime: %02d/%02d/%02d %02d:%02d:%02d\r\nDuration: %d\r\n",
                id,
                index,
                AnalysisEvents[id][index].min,
                AnalysisEvents[id][index].max,
                AnalysisEvents[id][index].avg,
                AnalysisEvents[id][index].month,
                AnalysisEvents[id][index].day,
                AnalysisEvents[id][index].year,
                AnalysisEvents[id][index].hour,
                AnalysisEvents[id][index].min,
                AnalysisEvents[id][index].second,
                AnalysisEvents[id][index].duration
                );
        return index;
    }
    else
    {
        return 0;
    }
}

2 个答案:

答案 0 :(得分:6)

参数12是:

AnalysisEvents[id][index].min,

你可能想要:

AnalysisEvents[id][index].minute,

答案 1 :(得分:1)

在您的情况下,违规部分是

 %02d/%02d/%02d %02d:%02d:%02d\r\
                      ^^^

相应的参数是AnalysisEvents[id][index].min,类型为double。您使用了%d

FWIW,也许你想要的答案

“警告消息中的参数号是提供给sprintf()的参数号的总和,从buffer本身开始计算,而不仅仅是作为格式参数提供的值。”