指向字符串数组的 C++ 指针
c++ pointer to array of strings
看看这段代码: 我正在尝试从控制台读取许多字符串并将它们存储在动态数组中。
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])
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错