I'm trying to understand and learn linked lists, but I'm having trouble conceptualizing the concept of a pointer to a struct. I think maybe it would help if I understood how these things are stored in memory. So for example, if one had this code:
1 2 3 4 5 6 7 8 9 10 11
struct node {
int info;
node *link;
};
class linkedList {
private:
node *top;
};
Where is *top pointing to in terms of memory? In other words, how does *top know to point to the *link part of struct rather than the info part of struct?
'top' is not pointing to 'link'. Since it is a 'node*' it will point to a block of memory which is big enough to hold data for all the members of the struct 'node'. When you deference 'top' you get a 'node' object. If you want to use a member of 'node' you'll have to explicitly write that
1 2 3
node* a_node = new node(); // a_node points to a freshly allocated node
a_node->info = 0; // note that I explicitly write that I want to use the 'info' part of a node
a_node->link = nullptr; // same as above