无法删除stuct指针内的指针数组(c ++)

时间:2018-05-08 03:25:18

标签: c++

我在这里遇到了语法问题。我们正在研究当前类中的结构和指针,其任务是创建一个单个结构的动态数组,其中包含一个指针数组,在程序结束时分配和删除它们。 (希望这是有道理的)

以下是我正在使用的代码的信息,请注意分数输入的工作原理:

std::cin << stuArray[i].stuScore[j]

但是以类似的方式删除,不会:

delete[] stuArray[count].stuScore[j];

删除代码:

    do
{
    for (unsigned short j = 0; j < numTests; j++)
    {
        delete[] stuArray[count].stuScore[0]; //Syntax???????
    }
    count++;
} while (count < numStudents);
delete[] stuArray;

分数录入代码(有效)

bool ScoreEntry(Student * stuArray, unsigned short numStudents, unsigned short numTests)
{
    //Local Variables
    unsigned short idTempChoice = 0;

    //Get Id Number
    std::cout << "\nChoose a student by ID and enter the test scores: ";
    std::cin >> idTempChoice;

    //Id lookup
    for (unsigned short i = 0; i < numStudents; i++)
    {
        //Id Check
        if (idTempChoice == stuArray[i].stuId)
        {
            std::cout << "Student selected: " << stuArray[i].stuName << std::endl;

            //Score Entry
            for (unsigned short j = 0; j < numTests; j++)
            {
                std::cout << "Test " << j + 1 << "'s Score: ";
                std::cin >> stuArray[i].stuScore[j];
            }//End For Loop j

            return true;
        }
    }//End For Loop i

    //Student Id not found
    std::cout << "Student not found!\n";
    return false;
}

分配代码(结构):

void MemAllocation(Student * &stuArray, unsigned short &numStudents)
{
    //Get Number of students
    std::cout << "How many students have taken the test: ";
    std::cin >> numStudents;
    std::cout << std::endl;

    //Dynamically allocate pointers
    stuArray = new Student[numStudents];
}

分配代码(结构中的指针):

for (unsigned short i = 0; i < numTests; i++) //Allocate Dynamic array for each student
    {
        stuArray[i].stuScore = new float[numTests];
    }

这是您需要引用的所有代码,这不是它的语法问题:)

2 个答案:

答案 0 :(得分:1)

尝试delete[] stuArray[count].stuScore;

不是delete[] stuArray[count].stuScore[j];

delete []用于删除分配有new type[n]

的数组

您想删除指向内存的指针,而不是实际的内存。

答案 1 :(得分:0)

您可以删除delete[] stuArray[count].stuScore但不能删除delete[] stuArray[count].stuScore[j] - drescherjm

修正使用:

do
{
    delete[] stuArray[count].stuScore;
    count++;
} while (count < numTests);