How do you concatenate or copy char* together?
char* totalLine;
const char* line1 = "hello";
const char* line2 = "world";
strcpy(totalLine,line1);
strcat(totalLine,line2);
This code produces an error!
segmentation fault
I would guess that i would need to allocate memory to totalLine?
Another question is that does the following copy memory or copy data?
char* totalLine;
const char* line1 = "hello";
totalLine = line1;
Thanks in advance! :)
I would guess that i would need to allocate memory to totalLine?
Yes, you guessed correctly. totalLine
is an uninitialized pointer, so those strcpy
calls are attempting to write to somewhere random in memory.
Luckily, as you've tagged this C++, you don't need to bother with all that. Simply do this:
#include <string>
std::string line1 = "hello";
std::string line2 = "world";
std::string totalLine = line1 + line2;
No memory management required.
does the following copy memory or copy data?
I think you mean "is the underlying string copied, or just the pointer?". If so, then just the pointer.
Yes, you need to allocate memory to totalLine
. This is one way to do it; it happens to be my recommended way to do it, but there are many other ways which are just as good.
const char *line1 = "hello";
const char *line2 = "world";
size_t len1 = strlen(line1);
size_t len2 = strlen(line2);
char *totalLine = malloc(len1 + len2 + 1);
if (!totalLine) abort();
memcpy(totalLine, line1, len1);
memcpy(totalLine + len1, line2, len2);
totalLine[len1 + len2] = '\0';
[EDIT: I wrote this answer assuming this was a C question. In C++, as Oli recommends, just use std::string
. ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With