Heim > Fragen und Antworten > Hauptteil
Der Code lautet wie folgt:
void CopyStr(char *&destination, char *&source) {
int sz = strlen(source) + 1;//此处引发异常!!
destination = new char[sz];
for (unsigned i = 0; source[i] != 'Rrreee'; i++)
destination[i] = source[i];
destination[sz - 1] = 'Rrreee';
return;
}
Data::Data(Data &adata) {
CopyStr(adata.P_name, P_name);
CopyStr(adata.address, address);
CopyStr(adata.number, number);
}
Codebeschreibung: Die Datenklasse hat jetzt drei char*-Mitglieder, nämlich P_name, Adresse und Nummer.
Zusammengestellte Bilder:
Bitte gib mir die Antwort, danke! !
伊谢尔伦2017-05-31 10:41:26
首先char *&source这种参数改为char *const &source
,其次CopyStr(adata.P_name, P_name),这种改为CopyStr(P_name, adata.P_name)。
这是我测试的代码,直接可以运行:
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
using std::strlen;
class Data
{
public:
char *a = "";
char *b = "";
char *c = "";
Data(char *a, char *b, char *c):a(a),b(b),c(c) {};
Data(Data const &data);
};
int CopyStr(char * &des, char * const &source)
{
int sz = strlen(source) + 1;
des = new char(sz);
for (unsigned i = 0; source[i] != '\0'; i++)
*(des +i) = source[i];
*(des+sz - 1) = '\0';
return 0;
}
Data::Data(Data const &data)
{
CopyStr(a, data.a);
CopyStr(b, data.b);
CopyStr(c, data.c);
}
int main()
{
Data data = Data("abcd", "b", "c");
char * p = "232323";
Data data2 = Data(data);
char * p2 = "1232";
CopyStr(p2, p);
cout << p2 << endl;
cout << data.a << endl;
cout << data2.a << endl;
return 0;
}
phpcn_u15822017-05-31 10:41:26
vs会用0xCCCCCCCC填充未初始化的内存区域(这也是烫烫烫
的由来);
考虑到你访问到了0xCCCCCCCC,所以要不就是你传进去了个非法指针,要不就是这个char*
指针对应的字符串没有以'0'结尾;
可以试着输出一下source
的值,然后逐字节输出指针所指向的数据试试