指向字符串数组的 C++ 指针

c++ pointer to array of strings

本文关键字:C++ 指针 数组 字符串      更新时间:2023-10-16

看看这段代码: 我正在尝试从控制台读取许多字符串并将它们存储在动态数组中。

int Doctor::addPatients()
{
  string* names = NULL;
  int num;
  cout << "how many patients are to be added? ";
  cin >> num;
  numPatients=num;
  names = new string[numPatients];
  for(int i=0;i++;i<numPatients){
    cout << "enter the next patient's name: ";
    cin.clear();
    cin >> names[i];
  }
  patients = names; //patients is a private member variable of class Doctor
}

当我执行此代码时,出现以下错误:

malloc: *** error for object 0x10c100898: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

任何帮助都非常感谢

for(int i=0;i++;i<numPatients)  // Condition is the second expression in for syntax

语法错误。

for(int i=0;i<numPatients; i++)

你用的是什么编译器?您应该得到编译错误而不是运行时错误。你还写了一个复制构造函数吗?有关详细信息,请参阅三法则。要简化作业,请使用 std::vector<std::string>

你不初始化整数 i

在 for 语句中,for(int i;i++;i<numPatients)

i应初始化为 0,条件应为第二个参数正确的格式应该是 -

for(int i=0;i<numPatients;i++)

cin不是获取字符串输入的好方法。 CIN 仅在看到空格字符(空格、换行符、制表符等)之前读取。或者使用获取线函数 -

语法:

getline(cin,names[i])