How to copy or concatenate two char*

mister picture mister · May 15, 2012 · Viewed 26.6k times · Source

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! :)

Answer

Oliver Charlesworth picture Oliver Charlesworth · May 15, 2012

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.