Проблема при попытке доступа к объекту структуры внутри массива структур - PullRequest
0 голосов
/ 12 апреля 2020

У меня проблемы с попыткой вставить sh элемент в мою очередь, и я не могу понять, что не так. У меня есть собственный тип данных, и я почти уверен, что не пытаюсь получить доступ к памяти, которая не была выделена, или к любому другому связанному сценарию ios.

Queue.h

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

class 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
...