如何复制或连接两个char * [英] How to copy or concatenate two char*

查看:157
本文介绍了如何复制或连接两个char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何连接或复制char *?

How do you concatenate or copy char* together?

char* totalLine;

const char* line1 = "hello";
const char* line2 = "world";

strcpy(totalLine,line1);
strcat(totalLine,line2);

此代码产生错误!

segmentation fault

我猜想我需要分配内存to totalLine?

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;

预先感谢! :)

推荐答案


我猜想我需要分配内存给totalLine?

I would guess that i would need to allocate memory to totalLine?

是的,你猜的正确。 totalLine 是一个未初始化的指针,因此 strcpy 调用试图写入内存中随机的某处。

Yes, you guessed correctly. totalLine is an uninitialized pointer, so those strcpy calls are attempting to write to somewhere random in memory.

幸运的是,你已经标记了这个C ++,你不需要麻烦这一切。只需这样做:

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;

不需要内存管理。


会执行以下复制内存或复制数据?

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.

这篇关于如何复制或连接两个char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆