我正在使用动态堆分配来创建课堂工具来添加学生。程序提示用户/教师输入学生的姓名,并将他们分配给一个数组。
我测试了调用负责分配更大堆数组的while
函数的add
循环。程序输出按预期添加的学生列表,并可以创建更大的堆数组。
然而,当我尝试添加第11名学生时,我收到此消息THRD 1 EXC_BAD_ACCESS code1
。我读到这意味着该程序无法再访问内存块,但我很困惑为什么这会发生在第11名学生?任何调试建议都非常感谢。感谢您的耐心等待,我仍然习惯了C ++
/*
Dynamic Heap Allocation using pointers
*/
#include <iostream>
#include <string>
using namespace std;
void add(string arr[],int& studs,int& counter){
//copies student names to a bigger array
studs+=10; //vs passing by value
string* big_brotha = new string[studs]; // a holder
for(int i=0;i<counter;i++){
big_brotha[i]=arr[i];
}
delete[] arr;
arr = big_brotha;
}
int main() {
int n=5;
int count=0;
string name;
bool cont = true;
char option;
string* arrayofpointers = new string[n];
cout << "enter student names. Enter Q to quit " << endl;
while (cont){
cout << "enter student name for seat number " << count << endl;
cin >> name;
if (name=="Q"){
for (int i=0;i<count;i++){
cout << arrayofpointers[i] << endl;
}
break;
}
cout << "is the counter less than array size? " << (count<n) << endl;
if (count>=n){ //time to make the array bigger!
cout << "time to make the array bigger!" << endl;
add(arrayofpointers,n,count);
cout << "the array is now this big " << n << endl;
arrayofpointers[count]=name;
}
else{
arrayofpointers[count]=name; //no longer possible to access memory
}
count++;
}
return 0;
}