ZBLOG

text6.c: In function ‘main’: text6.c:74:15: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t {aka long unsigned int}’ [-Wformat=] printf("queue_put a node , used: %d\n", strlen(str) + 1 + ts); ...

这些警告提示您使用 %d 格式说明符来打印 size_t 类型的值,但 size_t 是无符号长整型,使用 %lu 来格式化打印。这是因为在不同的平台上,size_t 的大小可能不同,因此需要正确匹配格式说明符。可以通过将 %d 修改为 %zu(专门用于 size_t)或 %lu(适用于 unsigned long) 进行修复。

以下是修改后的代码片段,以消除这些警告:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct DataNode {
    char *data;
    struct DataNode *next;
} DataNode;

typedef struct {
    DataNode *head;
    DataNode *tail;
} Que;

// 初始化队列
void queue_init(Que *myroot) {
    myroot->head = NULL;
    myroot->tail = NULL;
}

// 将节点放入队列
void queue_put(Que *myroot, DataNode *myDataNode) {
    if (myroot->tail != NULL) {
        myroot->tail->next = myDataNode; // 连接新节点
    }
    myroot->tail = myDataNode; // 更新尾指针

    if (myroot->head == NULL) { 
        myroot->head = myDataNode; // 如果头为空,设置为新节点
    }
}

// 从队列中获取节点
DataNode* queue_get(Que *myroot) {
    DataNode *myDataNode = myroot->head;

    if (myDataNode != NULL) {
        myroot->head = myroot->head->next; // 更新头指针
        myDataNode->next = NULL; // 清空被取出节点的下一个指针
        
        if (myroot->head == NULL) {
            myroot->tail = NULL; // 如果头变为空,则更新尾指针
        }
    }

    return myDataNode; // 返回被取出的节点
}

int main() {
    Que *myroot;
    DataNode *tmpNode;
    char str[1024];
    
    size_t qs, ts;
    
    qs = sizeof(Que);
    ts = sizeof(DataNode);
    
   printf("sizeof(Que): %zu, sizeof(DataNode): %zu\n", qs, ts);

   myroot = (Que *)malloc(qs); // 分配内存给队列
   queue_init(myroot); // 初始化队列

   for (int i = 0; i < 4; i++) {
       scanf("%s", str);
       tmpNode = (DataNode *)malloc(ts); // 分配内存给数据节点
      
       tmpNode->data = (char *)malloc(strlen(str) + 1); 
       strcpy(tmpNode->data, str);
       tmpNode->next = NULL;

       queue_put(myroot, tmpNode); // 将数据节点放入队列中

       printf("queue_put a node , used: %zu\n", strlen(str) + 1 + ts);
   }

   while (myroot->tail != NULL) { 
       tmpNode = queue_get(myroot); // 从队列中获取数据节点

       printf("queue_get a node: %s, freed: %zu\n", tmpNode->data,
              strlen(tmpNode->data) + 1 + ts);

       free(tmpNode->data); 
       free(tmpNode); // 释放内存
   }

   free(myroot); // 最后释放整个队列的内存

   return 0; // 返回成功退出程序
}

更改内容:

  • printf() 中,将 %d 替换为 %zu 来输出 size_t 类型的变量,以避免编译时的类型不匹配警告。

通过上述更改,您的代码将能够安全地处理并输出与平台相关的大小值,而不会引发类型不匹配的警告。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=19160

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?