How to copy or concatenate two char*

戏子无情 提交于 2019-12-06 02:41:58

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

totalLine has a garbage value

const char* Line1{ "Hallo" };  
const char* Line2{ "World" };   
char* TotalLine{ new char[strlen(Line1) + strlen(Line2) + 1] };

TotalLine = strcpy(TotalLine, Line1);
TotalLine = strcat(TotalLine, Line2);

Note=> If you work on Visual Studio you need #define _CRT_SECURE_NO_WARNINGS

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!