Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy or concatenate two char*

Tags:

c++

strcpy

strcat

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

like image 616
mister Avatar asked Nov 28 '22 09:11

mister


2 Answers

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.

like image 164
Oliver Charlesworth Avatar answered Nov 30 '22 23:11

Oliver Charlesworth


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. ]

like image 36
zwol Avatar answered Nov 30 '22 21:11

zwol