【发布时间】:2021-04-14 03:56:44
【问题描述】:
我想编写一个程序,创建一个函数,将两个字符串连接成一个字符串。但是,我的程序没有返回任何值。
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
char* my_str_cat( char* s1, char* s2, char* combined ){
for(int i = 0;i<strlen(s1);i++){
combined[i]=s1[i];
}
for (int j=0;j<strlen(s2);j++){
combined[strlen(s1)+j]=s2[j];
}
return combined;
}
int main(){
char s1[100];
char s2[100];
char** combined = new char*;
cout<<"Enter s1: "<<endl;
cin.getline(s1,100);
cout<<s1<<endl;
cout<<"Enter s2: "<<endl;
cin.getline(s2,100);
my_str_cat(s1,s2,*combined);
delete combined;
return 0;
}
【问题讨论】:
-
因为您从不为
*combined保留任何内存,这可能应该是char *,而不是char**。 -
为什么
combined是char**开头?为什么不是普通的char*?或者更好的是,std::string? -
std::string有一个operator+连接。如果您想将此作为练习,则需要为组合字符串提供一些字符,而不仅仅是指向字符的指针 -
对了,为什么不写一些代码来检查
my_str_cat的结果呢? -
当我尝试 char* 时出现错误
标签: c++ dynamic-memory-allocation c-strings string-concatenation function-definition