0

I'm having trouble interpreting the code for a linked list of students passed out as preparation for pset5, and would like to know if someone could explain what I am missing.

The structs are as follows ...

typedef struct node
{
    student* student;
    struct node* next;

}node;

And ...

typedef struct
{
    int id;
    char* name;
    char* house;
}student;

Here's how I am thinking about this, and I know something is wrong. Two lines in particular are troubling me. First, node* ptr = first. The variable ptr should hold only the address of node* first which has been set to null with node* first = NULL. The node pointer first has no "compartment" for any other data (since we always draw it as a single box, so node* ptr = first means ptr only contains an address, which is NULL. Similarly, node* predptr = ptr indicates predptr should hold just the address of ptr. Here's the big problem: based on predptr->student != NULL it seems predptr holds a lot more than an address, even though it's a pointer. It appears to have access to everything that ptr contains, though no dereferencing occurs. Could someone tell me how best to think about this code in layman's terms?

// free list before quitting
node* ptr = first;
while (ptr != NULL);
{
    node* predptr = ptr;
    ptr = ptr->next;
    if (pedptr->student != NULL)
    { etc
1

first, I wanna make it clear that there is a difference between the address of a pointer and the address stored in a pointer (aka the address that the pointer points to).

pointers are special type of variables that can store memory addresses. where does a pointer store an address? in a memory location somewhere that also has an address.

int i = 10; // suppose this is stored in address 100
int *ptr = &i; // stores (aka points to) 100, but its address is different
               // (e.g., address 104)

another thing is that setting one pointer of some type to another of the same type makes both pointers point to the same location in memory (store the same address, but still have different addresses).

int *anotherPtr = ptr; // anotherPtr now stores (aka points to 100), but its address is different 
                       // (e.g., address 108)

in case of a pointer to a struct, let's call that p, you can access the members of the struct through p using the so-called arrow operator.

typedef struct mystruct {
    char member;
} mystruct;

mystruct s;
s.member = 'k'; // s.member is now 'k'

mystruct *p = &s; // p now points to s
p->member = 'a'; // same as (*p).member = 'a', only shorter
                 // s.member is now 'a'

watch the shorts on structs (https://youtu.be/6RLxPdZ59y0) and pointers (https://youtu.be/yOdd3uYC--A) for more information!

1
  • Thanks for the thorough response! I watched several videos last night. Things are much clearer. Cheers!
    – Ryan
    May 18 '16 at 11:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .