运行此功能时程序崩溃

时间:2014-12-09 03:51:20

标签: c++ pointers struct

我在将指针缠绕在指针上并使用结构中的指针时遇到了麻烦。首先,我不知道我是否在结构中正确使用指针。另外,当我运行我的程序时,它似乎在达到readRecords时崩溃,所以它一定有问题。由于我不太清楚如何使用指针,我可能在这里做错了...我只是不知道是什么。有什么方法可以编辑这个功能,这样我就不会崩溃吗?此外,我必须保留这些功能,因为它们是我项目要求的一部分。

struct testScores
{
    string name;
    string idNum;
    int testNum;
    int *tests;    // This is supposed to be a dynamically allocated array
    double average;
    char grade;
};

[...]

void arrStruct(testScores*& sPtr)
{
    sPtr = new testScores[];
}

void readRecords(ifstream& data, int record, testScores*& sPtr)
{
    for (int count = 0; count < record; count++)
    {
        data >> sPtr[count].name;
        data >> sPtr[count].idNum;
        data >> sPtr[count].testNum;
        sPtr[count].tests = new int[sPtr[count].testNum];   // tests is dynamically allocated (?)
        for (int tCount = 0; tCount < sPtr[count].testNum; tCount++)
            data >> sPtr[count].tests[tCount];
    }
}

1 个答案:

答案 0 :(得分:1)

sPtr = new testScores[];

这似乎是非法语法 - 数组new需要一个下标来知道要分配多少空间。 通常这至少为1,在您的情况下,编译器可能会将此解释为new testScores[0],它确实返回有效指针,但不从堆中分配任何内存。

当然sPtr所指向的任何后续内存访问都是超出界限并导致未定义的行为(在您的情况下是崩溃)。