gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:24:12 24 4
gpt4 key购买 nike

看看这段代码:我试图从控制台读取一些字符串并将它们存储在一个动态数组中。

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++)

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

关于c++ 指向字符串数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12709467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com