#include <iostream>
#include <Windows.h>
//包含检测头文件
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
#include <Windows.h>
#include <string>
#include <stdio.h>
//接管new操作符
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ ,__LINE__)
#define new DBG_NEW
#endif
#endif
using namespace std;
int main(void){
方法一
/*string str1 , str2, str3;
string *str = new string[1024];
cout << "请输入第一段文字:";
cin >> str1;
cout << "请输入第二段文字:";
cin >> str2;
*str = str1 + str2;
cout << *str << endl;
cout << "请输入第三段文字:";
cin >> str3;
*str = *str + str3;
cout << *str << endl;
delete[] str;
*/
方法二
string p1,p2,p3;
cout << "请输入第一段文字:";
cin >> p1;
char *p11 = new char(p1.length()+1);
strcpy(p11, (char*)p1.c_str());
cout << "请输入第二段文字:";
cin >> p2;
char *p22 = new char(p2.length()+1);
strcpy(p22, (char*)p2.c_str());
cout << "请输入第三段文字:";
cin >> p3;
char *p33 = new char(p3.length()+1);
strcpy(p33, (char*)p3.c_str());
cout<< p11 << p22 << p33 << endl;
delete p11;
delete p22;
delete p33;
//在代码运行调试输出窗口输出泄漏提示信息
_CrtDumpMemoryLeaks();
system("pause");
return 0;
}
该代码示例展示了两种方法在C++中处理动态内存和字符串拼接。方法一使用`new`操作符动态分配字符串数组,并结合使用`cin`进行输入和拼接。方法二涉及使用`new`分配字符数组来存储字符串,然后使用`strcpy`进行拼接。最后,通过`_CrtDumpMemoryLeaks`检查内存泄漏情况。

被折叠的 条评论
为什么被折叠?



