Reputation: 84
I'm trying to combine two strings with a delimiter between them using strncat
but i'm not able to get the exact results .Please let me know why is it getting wrong .
#include <stdio.h>
#include <string.h>
int main()
{
char Buff[100];
memset(Buff,0,sizeof(Buff));
char *Ip="192.168.4.10";
char *Ip2="192.168.4.20";
strcpy(Buff,Ip);
strncat(Buff,"||",sizeof("||"));
strncat(Buff,Ip2,sizeof(Ip2));
printf("%s",Buff);
}
I'm getting the output as 192.168.4.10||192.
instead of the concatenation of the two data.What could have gone wrong . Is there still more efficient way of doing this ?
Upvotes: 0
Views: 189
Reputation: 58281
The expression strncat(Buff,Ip2, sizeof(Ip2));
is wrong because sizeof(Ip2)
gives size of Ip2
pointer but not length of string pointed by Ip2
.
In your system size of char pointer is 4 bytes that is why strncat() could append only 4 chars from string Ip2
(1
, 9
, 2
, .
).
You are confuse between sizeof()
operator and length of string. Note sizeof("||")
gives you 3
( that is number of bytes "||"
takes) while it's length is 2
.
Additionally, the first strncat(Buff,"||",sizeof("||"));
working well because third char is \0
.
To rectify your code use strlen(char *)
function from string.h
header file:
strncat(Buff, "||", strlen("||"));
strncat(Buff, Ip2, strlen(Ip2));
Upvotes: 2