Reputation: 23
I am trying to use a doubly linked list with a header struct. I believe the header struct is simply supposed to hold a count of how many structs have been created in the list, and the first and last nodes. Now I see two problems. One is connecting the header struct to the subsequent structs and the second is accessing a nested struct that i have within my list nodes (sentry). If anyone could shed some light on what I might be doing wrong it would be greatly appreciated. Code is below.
#include <iostream>
using namespace std;
typedef struct sentry sentry;
struct stud{
string name;
char grade;
};
struct slist {
int length;
sentry *first;
sentry *last;
};
struct sentry {
slist *list;
sentry *next;
sentry *prev;
stud *student;
};
int main(int argc, char** argv) {
slist list;
sentry *n;
n = new sentry;
// Full initialization of the header node.
list.first = n;
list.last = n;
list.length = 0;
n->prev = NULL;
n->next = NULL;
n->list = list->last;
n->student->name = "test";
n->student->grade = 'A';
cout << n->student->name << '\n';
cout << n->student->grade << '\n';
return 0;
}
Upvotes: 1
Views: 302
Reputation: 2237
Why don't you modify your struct sentry to not include slist *list
?
Why is having a 2-way relationship between sentry
and slist
necessary? It makes it tedious to maintain, to read and update the values inside the list of the sentry. Nevermind, deallocating the memory on the heap to avoid memory leaks. Why not have slist
(the header) only have information about the sentry
. In this way you remove the complexity of a double binding between sentry
and slist
.
struct sentry {
sentry *next;
sentry *prev;
stud *student;
};
Upvotes: 1