I need to put "Hello World" in str3. How can I do this ?
const char *one = "Hello ";
char *two = "World";
char *str3;
I need to put "Hello World" in str3. How can I do this ?
const char *one = "Hello ";
char *two = "World";
char *str3;
You have to allocate void* malloc (size_t size);
for str3 first then you can use sprintf
to write in a string.
char *str3 = malloc(strlen(one) + strlen(two) + 1);
sprintf(str3, "%s%s", one, two); // ^ \0 termination
Adding @Nik Bougalis Suggestion:
One should know dynamic memory allocation in C. In my code I allocated using malloc()
so latter in code when I don't need str3
we should explicitly deallocate memory using free()
in C.
Also to avoid buffer-overflow always use snprintf
instead of sprintf
: So re-writing code as follows:
int length = strlen(one) + strlen(two) + 1;
char *str3 = malloc(length * sizeof(char));
snprintf(str3, length, "%s%s", one, two);
// write more code that uses str3
free(str3);
// now don't uses `str3`'s allocated memory
Read a book about C.
str3 = malloc(strlen(one) + strlen(two) + 1) ; // +1 for the 0 terminator
strcpy(str3, one) ;
strcat(str3, two) ;
...
free(str3) ; // frees allocated space when you are finished.
std::vector<char> v;
v.insert(v.end(), one, one + strlen(one));
v.insert(v.end(), two, two + strlen(two));
v.push_back('\0');
str3 = v.data();
String literals like "Hello"
are stored in read-only memory, so you need to copy them somewhere where they can be modified.
So you must first allocate memory where the strings are to be stored. A simply char array will do. Then use strcpy() and strcat() to copy the string literals into that array.