为什么我的指针数组显示“索引超出有效索引范围”?

问题描述

我正在做一个学校项目,我试图将每个学生对象“ objStudent [5]”添加到指针数组“ classRosterArray”。当我尝试在构造函数“ Roster”中初始化指针时。我收到警告“索引5超出有效索引范围”。这是我第一次学习C ++,所以我不确定该怎么做。

这是我创建了指针数组“ classRosterArray”的花名册类

//roster.h
#pragma once
#include <string>
using namespace std;

class Roster {
private:
string* classRosterArray[5];
public:
    Roster();
    void ParseStudentData();
    void PrintAll();
};

消息“索引超出范围”出现在Roster :: Roster构造函数中

//roster.cpp
#include "roster.h"
#include "student.h"

//studentData table
const string studentData[5] = {
"A1,John,Smith,John1989@gm ail.com,20,30,35,40,SECURITY","A2,Suzan,Erickson,Erickson_1990@gmailcom,19,50,NETWORK","A3,Jack,Napoli,The_lawyer99yahoo.com,33,SOFTWARE","A4,Erin,Black,Erin.black@comcast.net,22,58,"A5,Joe,Shmoe,jshmoe@google.com,34,SOFTWARE"
};

//Object for each student in the studentData table
Student objStudent[5];

Roster::Roster()
{
    classRosterArray[5] = nullptr; //index out of range
    classRosterArray[5] = new string[5]; //tried using this to solve issue taking stabs in the dark
}

//Function to parse each set of student data in the studentData table
void Roster::ParseStudentData() {
    for (int i = 0; i < 5; i++) {
        size_t rhs = studentData[i].find(",");
        objStudent[i].SetStudentID(studentData[i].substr(0,rhs));

        size_t lhs = rhs + 1;
        rhs = studentData[i].find(",",lhs);
        objStudent[i].SetFirstName(studentData[i].substr(lhs,rhs - lhs));

        lhs = rhs + 1;
        rhs = studentData[i].find(",lhs);
        objStudent[i].SetLastName(studentData[i].substr(lhs,lhs);
        objStudent[i].SetEmailAddress(studentData[i].substr(lhs,lhs);
        objStudent[i].SetAge(stoi(studentData[i].substr(lhs,rhs - lhs)));      
    }
}

void Roster::PrintAll() {
    ParseStudentData(); //Call ParseStudentData function to parse studentData table
}

解决方法

您遇到此错误:

“索引超出有效索引范围”

因为创建的array由5个元素组成,所以您只有 index 从0到4。

访问您特定的array的最大有效索引为4。

如果您更改此行:

classRosterArray[5] = nullptr;

收件人:

classRosterArray[4] = nullptr;

应该修复它。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...