C char阵列串联
C++ char array concatenation
我试图超载加号以加以连接两个字符串,但我一直遇到错误。
vs 2010给出断言失败消息:"表达式:(l" buffer toom smalte"&& 0);文件: f: dd vctools crt_bld self_x86 crt src src tcscat_s.inl;行: 42。
您认为我的代码有什么问题?
#include "stdafx.h"
class MyString{
int l; // the length of the array pointed by buf
char *buf; //pointer to a char array
public:
...
MyString(char *);
friend MyString operator+(MyString &,MyString &);
...
};
MyString::MyString(char *p)
{
buf=new char[strlen(p)+1];
strcpy_s(buf,strlen(p)+1,p);
l=strlen(p)+1;
}
MyString operator+(const MyString &a,const MyString &b)
{
MyString result("");
result.l=a.l+b.l;
delete[] result.buf;
result.buf=new char[result.l+1];
result.buf[0]=' ';
strcat_s(result.buf,result.l+1,a.buf);
strcat_s(result.buf,result.l+1,b.buf);
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
MyString a("hello"),b("world"),c("");
c=a+b;
system("pause");
return 0;
}
现在起作用!谢谢大家!
strcat_s(result->buf,strlen(a.buf),a.buf); strcat_s(result->buf,strlen(b.buf),b.buf);
strcat_s
的第二个参数是目标缓冲区的大小,而不是应附加的字符串大小。因此,您需要将其更改为
strcat_s(result->buf,result->l+1,a.buf);
strcat_s(result->buf,result->l+1,b.buf);
正如其他人所指出的,其余的操作员 实现也被打破了。新的实例,然后按值返回它是胡说八道。只需在堆栈上实例化结果并按值返回。
在运算符 变量" mystring结果"中被声明在堆栈上,随后通过参考返回,这很糟糕。
然后对OP进行了编辑。变量"结果"不再在堆栈上声明,而是在堆上分配。但是,然后有记忆泄漏。
在这里要做的正确的事情是按值返回,并在堆栈上声明" mystring结果"。还要确保您有一个复制构造函数。这是一个事。
您还应该使构造函数采用" const char*"。
应该是 result.buf=new char[result.l+1];
允许null字符。
相关文章:
- 将动态阵列中的字符与char进行比较
- Arduino(C )condenate char*阵列与float数组
- char,const char*阵列问题,用于mqtt client.publish
- 为什么Xor-ing两个“ char”阵列显示垃圾位
- 从char阵列中提取十六进制数字
- 我如何使我的循环转到char*阵列的尽头,并将每个城市都放在链接的列表中(城市被划分为白色的空间)
- CIN正在为char阵列工作,但不为int阵列工作
- 如何在C/ C 中比较两个char的两个2D阵列
- 为什么在使用SizeOf进行同一char阵列时会得到各种结果
- 如何打印char阵列的地址
- 如何将char阵列的中间单词更改为向后
- 我如何格式化十六进制中“未签名char”阵列的值
- 创建char阵列时,其长度与所需的长度不同
- C 2D char阵列有时会在随机位置复制数据
- 如何创建一个构造函数,该构造函数吸收char阵列
- Char阵列中的特定索引的C 拉动签名整数
- 在C 中乘以两个char阵列
- 无效的char阵列分配
- 如何使用3D char数组调整双指针2D char阵列的大小
- 如何将浮点转换为长度为4的字节阵列(char*的阵列)