【问题标题】:C++ char* error, program crashesC++ char* 错误,程序崩溃
【发布时间】:2014-10-28 22:05:58
【问题描述】:

我正在尝试编写一个程序来存储名称的 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); 错误

如果有人可以修改我的代码并帮助我,我将不胜感激

谢谢

【问题讨论】:

  • 不应该names = new char[60];names[i] = new char[60]; 吗?其他错误是前一个错误的副作用。
  • 如果名称超过 59 个字符,祝您好运。
  • @alvits 谢谢 :),但我仍然在输入方面遇到错误。我的代码在 IDEOne - ideone.com/PAMwgw
  • 您的 input_name 未初始化。在您的情况下,将其设置为简单的字符串而不是指针会更容易。 char input_names[60];.
  • 如果你不想使用std::string,为什么还要使用C++?

标签: c++ string pointers char


【解决方案1】:

它是 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 在 cmets 中提到的,当名称超过 59 个字符时,您会遇到麻烦。加上 std::string 更方便 IMO。

【讨论】:

  • 如果我不执行input_name = new char[60];,为什么我的程序会崩溃?我的程序在cin &gt;&gt; input_name; strcpy(names[i],input_name) 崩溃了
  • 您刚刚声明了 input_name 应该是什么,但从未为其赋值。因为它是一个指针,所以它指向一个无效的内存地址。
  • @H4kor 此代码仍然使我的程序崩溃。我将names = new char*[10] 行修改为names = new char*[value],以便用户可以输入多个名称。如果用户想输入 5 个名字,效果很好,但是如果用户想输入 12 个名字,它会崩溃
【解决方案2】:

代码包含大量内存泄漏!实际上newed 的任何数据都应该是deleted。注意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
}

当然,在您发布的代码 sn-p 中,您尝试读入input_name,它指向无处:这将导致未定义(可能是一些崩溃)。

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多