Reputation: 101
Very simple question but within my code I have two char* variables.
char* port = "1100";
char* ip = inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
The first is a port number and the second tells the ip address of a given interface.
If I wanted to create a new variable say, char* both, why is it that I cannot say:
char* both = ip + port;
with the output of 172.21.8.179 1100? How can I get a new variable with that output? Thanks
Upvotes: 0
Views: 2848
Reputation: 3247
You can use sprintf()
function call
...
sprintf(char * buffer, const char * format, ...)
Dynamic
char* res = (char*)malloc(15);
char* str1 = "Hello ";
char* str2 = "World!";
sprintf(res, "%s%s", str1, str2);
puts(res); // Hello World!
Static
char res[15];
char str1[] = "Hello ";
char str2[] = "World!";
sprintf(res, "%s%s", str1, str2);
puts(res); // Hello World!
you're able to add integers into a C string too with the %d
format specifier.
Upvotes: 0
Reputation: 50120
you probably want to use snprintf
char buff[100];
snprintf(buff, sizeof(buff), "%s %s", port, ip);
Upvotes: 1
Reputation: 9270
You can't add two strings in C because, well, they're not actually strings. They're just pointers. And adding two pointers results in a pointer that points at the address that is the sum of the two original addresses.
To concatenate two char*
s together, you can use the strcat(char * destination, const char * source) function. Just make sure that your both
pointer is pointing to enough memory to actually hold the concatenated string!
Upvotes: 0