Reputation: 482
I wrote a code but I am not sure why the last printf gives unexpected result. My command line arguments were 12 and 15. The code is as follows:
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
struct in_addr adr, adr2;
int num, num2;
num = atoi(argv[1]);
num2 = atoi(argv[2]);
adr.s_addr = htonl(num);
adr2.s_addr = htonl(num2);
printf("%x %x\n", num, adr.s_addr); # c c000000
printf("%x %x\n", num2, adr2.s_addr); # f f000000
printf("%s\n", inet_ntoa(adr)); # 0.0.0.12
printf("%s\n", inet_ntoa(adr2)); # 0.0.0.15
printf("%s %s\n", inet_ntoa(adr), inet_ntoa(adr2)); # 0.0.0.12 0.0.0.12
return(0);
}
I expected the final output to be "0.0.0.12 0.0.0.15" but it's not so. Could anyone please help?
Upvotes: 3
Views: 540
Reputation: 225737
The inet_ntoa
function returns a pointer to a static buffer. In this case, the function is called twice as parameters to another function. The order of evaluation of function parameters is unspecified, so the contents of the static buffer will be whichever one happens to run last. And since it always returns the same buffer, the same thing will be printed twice.
So you can't call a function like this more that once without an intervening sequence point, i.e. separate statements, short circuit operators such as &&
or ||
, the comma operator, or the ternary operator.
In the case of this particular code, the two separate calls to printf
each with a single call to inet_ntoa
(as you do in the two prior lines) is the correct way to do this.
Also, if you plan on saving the result of this function someplace, you can't just save the pointer, since the data it points to will change each time inet_ntoa
is called. You would need to copy it using strcpy
or strdup
.
Upvotes: 6