Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying value from char pointer to a char array

I am having a pointer *ip_address_server which holds the ip address of the server :

   in_addr * address = (in_addr * )record->h_addr;
    char *ip_address_server = inet_ntoa(* address);

Clearly, when I use printf to print the value of it, it gets nicely printed.

printf("p address %s" , ip_address_server);

But now if I declare an array of say size 20 to hold the value then I need to copy the content from the pointer to the array.

char host_name[20];

To copy the value I used a for loop. But the value that I print later is not the right value.

for(int i = 0; ip_address_server[i] != '\0'; i++) 
        host_name[i] = ip_address_server[i];
    printf("hostname %s \n" , host_name);

I think there is some error with the terminating condition.

Am I wrong in my approach or is there any alternative way out for this?

like image 908
w2lame Avatar asked Dec 13 '22 18:12

w2lame


1 Answers

Your loop does not copy the '\0' byte.

Also, why don't you just use strcpy (or safer strncpy) or memcpy?

like image 129
逆さま Avatar answered Jan 01 '23 07:01

逆さま