尝试访问结构数组内部的结构对象时出现问题

时间:2020-04-12 15:45:18

标签: c++ arrays struct abstract-data-type

我在尝试将元素推入队列时遇到了麻烦,而且我无法弄清楚出了什么问题。我有一个自己定义的数据类型,我很确定我不会尝试访问尚未分配的内存或任何其他此类相关的方案。

Queue.h

typedef int TElem
//...
struct NodeDLLA {
TElem data;
int prev;
int next;
};

class Queue
{
//...
}

Queue.cpp

Queue::Queue() {
cap = 105;
len = 0;

head = -1;
tail = -1;

NodeDLLA* nodes = new NodeDLLA[cap];

nodes[0].prev = -1;                 
nodes[0].next = 1;
for (int i = 1; i < cap - 1; i++)
{
    nodes[i].prev = i - 1;
    nodes[i].next = i + 1;
}
nodes[cap - 1].prev = cap - 2;
nodes[cap - 1].next = -1;           

firstEmpty = 0; 

}
void Queue::push(TElem elem) {

    if (firstEmpty == -1)
    {
        //resize array...
    }

    cout << "check\n";
    cout << firstEmpty <<'\n';
    nodes[firstEmpty].data = elem; // here is the problem.
    cout << "check2\n";        
    // "check" is shown in the console terminal, but "check2" is not. 
    // firstEmpty is zero, thus there should be no problem of trying to access "illegal memory area"
    // ... rest of code
}

ShortTest.cpp

#include "ShortTest.h"
#include "Queue.h"
#include <assert.h>
#include<iostream>
using std::cout;
void testAll() {
    Queue q;
    assert(q.isEmpty() == true);
    q.push(5);
    cout << "So far so good" << '\n';
    /*
    q.push(1);
    q.push(10);
    assert(q.isEmpty() == false);
    assert(q.top() == 5);
    assert(q.pop() == 5);
    assert(q.top() == 1);
    assert(q.pop() == 1);
    assert(q.top() == 10);
    assert(q.pop() == 10);
    assert(q.isEmpty() == true);
    */
}

main.cpp

#include "Queue.h"
#include "ShortTest.h"
int main()
{
      testAll();
      return 0;   
}

控制台输出:

check

预期输出:

check
check2
So far so good

0 个答案:

没有答案