问题
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! :)
回答1:
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.
回答2:
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
. ]
回答3:
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
来源:https://stackoverflow.com/questions/10609326/how-to-copy-or-concatenate-two-char