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) 进行修复。

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

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. typedef struct DataNode {
  5. char *data;
  6. struct DataNode *next;
  7. } DataNode;
  8. typedef struct {
  9. DataNode *head;
  10. DataNode *tail;
  11. } Que;
  12. // 初始化队列
  13. void queue_init(Que *myroot) {
  14. myroot->head = NULL;
  15. myroot->tail = NULL;
  16. }
  17. // 将节点放入队列
  18. void queue_put(Que *myroot, DataNode *myDataNode) {
  19. if (myroot->tail != NULL) {
  20. myroot->tail->next = myDataNode; // 连接新节点
  21. }
  22. myroot->tail = myDataNode; // 更新尾指针
  23. if (myroot->head == NULL) {
  24. myroot->head = myDataNode; // 如果头为空,设置为新节点
  25. }
  26. }
  27. // 从队列中获取节点
  28. DataNode* queue_get(Que *myroot) {
  29. DataNode *myDataNode = myroot->head;
  30. if (myDataNode != NULL) {
  31. myroot->head = myroot->head->next; // 更新头指针
  32. myDataNode->next = NULL; // 清空被取出节点的下一个指针
  33. if (myroot->head == NULL) {
  34. myroot->tail = NULL; // 如果头变为空,则更新尾指针
  35. }
  36. }
  37. return myDataNode; // 返回被取出的节点
  38. }
  39. int main() {
  40. Que *myroot;
  41. DataNode *tmpNode;
  42. char str[1024];
  43. size_t qs, ts;
  44. qs = sizeof(Que);
  45. ts = sizeof(DataNode);
  46. printf("sizeof(Que): %zu, sizeof(DataNode): %zu\n", qs, ts);
  47. myroot = (Que *)malloc(qs); // 分配内存给队列
  48. queue_init(myroot); // 初始化队列
  49. for (int i = 0; i < 4; i++) {
  50. scanf("%s", str);
  51. tmpNode = (DataNode *)malloc(ts); // 分配内存给数据节点
  52. tmpNode->data = (char *)malloc(strlen(str) + 1);
  53. strcpy(tmpNode->data, str);
  54. tmpNode->next = NULL;
  55. queue_put(myroot, tmpNode); // 将数据节点放入队列中
  56. printf("queue_put a node , used: %zu\n", strlen(str) + 1 + ts);
  57. }
  58. while (myroot->tail != NULL) {
  59. tmpNode = queue_get(myroot); // 从队列中获取数据节点
  60. printf("queue_get a node: %s, freed: %zu\n", tmpNode->data,
  61. strlen(tmpNode->data) + 1 + ts);
  62. free(tmpNode->data);
  63. free(tmpNode); // 释放内存
  64. }
  65. free(myroot); // 最后释放整个队列的内存
  66. return 0; // 返回成功退出程序
  67. }

更改内容:

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

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?