C ++ char *错误,程序崩溃

时间:2014-10-28 22:05:59

标签: c++ string pointers char

我正在尝试编写一个存储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);错误

如果有人可以修改我的代码并帮助我

,我将不胜感激

由于

2 个答案:

答案 0 :(得分:2)

names[i] = new char[60];代替names = new char[60]; 而且您忘记使用input_name = new char[60];

初始化input_name
#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。

答案 1 :(得分:0)

代码包含大量内存泄漏!实际new编辑的任何数据都应为delete d。请注意,delete的形式需要与new的形式匹配,即,在分配数组对象时,数组对象需要使用例如delete[] names来释放。

当您读入char数组时,您需要确保数组中的数据量不超过,您可以通过设置流的宽度来限制要读取的字符数,例如:< / p>

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无处指出:这将导致未定义(可能是一些崩溃)。

相关问题