printf'ing 多个变量与单独 printf'ing 这些变量产生不同的输出[重复]

问题描述 投票:0回答:1

考虑到我有一个

struct iphdr *ip_hdr;

并且想要使用 printf 打印 Saddr/daddr。

使用两个单独的 printf 调用:

    printf("received packet from %s\n",
                    inet_ntoa(*(struct in_addr*)&ip_hdr->saddr));

    printf("received packet to %s\n",
                    inet_ntoa(*(struct in_addr*)&ip_hdr->daddr));

正确打印源/目标地址。

为什么

    printf("received packet from %s to %s\n",
                    inet_ntoa(*(struct in_addr*)&ip_hdr->saddr),
                    inet_ntoa(*(struct in_addr*)&ip_hdr->daddr));

print 使用第一个和第二个占位符的源地址(导致输出不正确)?

c++ c
1个回答
0
投票

inet_ntoa
调用返回一个指向静态缓冲区的指针,因此一次调用的结果会覆盖前一调用的结果。

所以当你这样做时:

printf("received packet from %s to %s\n",
                inet_ntoa(*(struct in_addr*)&ip_hdr->saddr),
                inet_ntoa(*(struct in_addr*)&ip_hdr->daddr));

inet_ntoa
的两次调用都返回相同的指针值,并且最后执行的调用(C 标准没有指定指定参数的顺序)将是两种情况下打印的结果。

© www.soinside.com 2019 - 2024. All rights reserved.