c++ - 不使用 vector 的动态字符串数组

标签 c++ arrays pointers dynamic

我正在做一项作业,我们必须创建一个“学生”对象,其中包含一个动态的“类(class)”成员数组,以便用户可以从一门类(class)进入数组中任意多门类(class)。我一直在尝试各种方法,只是无法让数组调整大小并接受新元素。这是我现在的代码:

cout << "Enter student name > ";
cin >> name;

Student firstStudent(name);

cout << endl << "Enter \"done\" when you are complete";
cout << endl << "Enter a new course : ";
cin >> course;

while (course != "done") {
    numCourses++;
    firstStudent.addElement(numCourses, course);//makes the array bigger
    cout << endl << "Enter a new course : ";
    cin >> course;

}//end while

成员变量和构造函数:

class Student
{
private:
   string name;//name of student

   string *dynArray = new string[1];//array

public:
Student::Student(string name)
{
   this->name = name;
   this->numC = 1;//initialized to one to start with    
}

调整大小并向数组添加元素:

void Student::addElement(int numCourses, string &course) {//DYNAMIC ARRAY
    if (numCourses > this->numC) {//checks if there are more courses than there is room in the array
       this->numC = numCourses; //this changes the member variable amount
       dynArray[numCourses] = course;//adds new course to array

       string *temp = new string[numC];//create bigger temp array

       temp = dynArray;//write original to temp

       delete[]dynArray; //this tells it that it's an array

       dynArray = temp;//make dynarray point to temp

    }
    else {
       dynArray[numCourses] = course;//adds new course to array
    }
}//end addElement

即使我设法摆脱了编译错误,它也经常会出现运行时错误。我确定它与指针/复制数组有关,但我只是在学习,还没有掌握这些概念。

编辑:dynArray[numCourses] = course;创建一个字符数组。即如果 course = "one", dynArray[0] = "o", dynArray[ 1] = "n", 等等。有人知道如何防止这种情况发生吗?

screenshot

最佳答案

第一行看起来不太正确的是:

dynArray[numCourses] = course;

在检查之前 numCurses > numC ,这意味着 dynArray[numCourses]越界访问内存(边界是 0numC - 1

另一件让我感兴趣的事情是 addElement方法需要 numCourses作为论据。我希望它的行为类似于 std::vector<T>::push_back .你确定这个参数是必要的吗?

我要评论的最后一件事是 dynArray 中的值不被复制。看看std::copy_n关于如何进行复制。

关于c++ - 不使用 vector 的动态字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33401648/

相关文章:

python - 更改 numpy 数组中字符串的位置

java - 用固定值填充一定比例的 Java 数组

c - 链表错误,指针

c++ - std::tuple get() 成员函数

java - 如何从 int 数组中删除零?

c - 从 C 中的指针和指向指针的指针中删除元素

c++ - 在 C++ 中将指针传递给函数

c++ - 不能 push_back 到 vector - 没有给出过载错误

c++ - 在 XCode 的 "Quick Help"中显示变量类型

c++ - 将字符串输入 RapidJson 以输出 JSON