连续多次调用inet_ntoa()结果重复


#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pcap.h> #include <arpa/inet.h> #include "myerror.h" int main(int argc, char* argv[]) { struct in_addr net_ip_address; struct in_addr net_mask_address; u_int32_t net_ip; u_int32_t net_mask; char errbuff[PCAP_ERRBUF_SIZE]; char* net_ip_string; char* net_mask_string; char* net_interface_string; if((net_interface_string=pcap_lookupdev(errbuff))==NULL) err_sys("lookup dev error"); if(pcap_lookupnet(net_interface_string,&net_ip,&net_mask,errbuff)!=0) err_sys("lookup net error"); net_ip_address.s_addr=net_ip; net_mask_address.s_addr=net_mask; if((net_ip_string=inet_ntoa(net_ip_address))==NULL) err_sys("ip ntoa error"); if((net_mask_string=inet_ntoa(net_mask_address))==NULL) err_sys("mask ntoa error"); printf("Network interface is %s ",net_interface_string); printf("Network ip is %s ",net_ip_string); printf("Network mask is %s ",net_mask_string); return 0; }

 在一个生存周期内,inet_ntoa返回一个char *,而这个char *的空间是在inet_ntoa里面静态分配的,所以inet_ntoa后面的调用会覆盖上一次的调用。

第一句printf的结果只能说明在printf里面的可变参数的求值是从右到左的,仅此而已。
Mr Wang Ever Work In Baidu mr.wang.self@gmail.com
原文地址:https://www.cnblogs.com/studystudent/p/3322442.html