![](/img/trans.png)
[英]Trying to split a char* in C++ using strok,program compiles but crashes
[英]C++ char* error, program crashes
我正在尝试编写一个存储名称的char数组的程序。
这是我的代码
#include <iostream>
#include <string.h>
using namespace std;
char **names;
char *input_name;
int main() {
names = new char*[10];
for(int i=0; i<10; i++){
names = new char[60];
cout << "Input name" << i << ": \n";
cin >> input_name;
strcpy(names[i],input_name);
cout << names[i] << "\n";
}
return 0;
}
首先,我得到的是cannot convert 'char*' to 'char**' in assignment names = new char[60];
错误。
同样,获得invalid conversion from 'char' to 'const char*' [-fpermissive] strcpy(names[i],input_name);
的invalid conversion from 'char' to 'const char*' [-fpermissive] strcpy(names[i],input_name);
错误
如果有人可以修改我的代码并帮助我,我将不胜感激
谢谢
它的names[i] = new char[60];
而不是names = new char[60];
而且您忘记了使用input_name = new char[60];
来初始化input_name input_name = new char[60];
#include <iostream>
#include <string.h>
using namespace std;
char **names;
char *input_name;
int main() {
names = new char*[10];
input_name = new char[60];
for(int i=0; i<10; i++){
names[i] = new char[60];
cout << "Input name" << i << ": \n";
cin >> input_name;
strcpy(names[i],input_name);
cout << names[i] << "\n";
}
return 0;
}
在使用c ++时,您可能应该考虑使用std :: string而不是char *。 正如PaulMcKenzie在评论中提到的那样,当名称长度超过59个字符时,您会遇到麻烦。 加std :: string是更方便的IMO。
该代码包含大量内存泄漏! 任何数据实际上new
ED,应delete
d。 注意, delete
的形式需要与new
的形式匹配,即,在分配数组对象时,需要使用例如delete[] names
释放数组对象。
读入char
数组时,需要确保不超过数组中的数据量,可以通过设置流的宽度来限制要读取的字符数,例如:
if (std::cin >> std::setw(60) >> names[i]) {
// OK - do something with the data
}
else {
// failed to read characters: do some error handling
}
当然,在您发布的代码段中,您尝试读取input_name
,但指向无处:这将导致未定义(可能会导致崩溃)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.