linked list pointer understanding!

This is fairly elementary, but I am not getting it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class slist {
slist() : h(nullptr){}
...
void prepend(char);   //adds to front of slist
slistelem* h;         //head of slist
};

struct slistelem {
char     data;
slistelem* next; 
};

void slist::prepend(char c)
{
  slistelem* temp = new slistelem;  //create element
  temp->next = h;                  //link to slist
  temp->data = c;                  
  h = temp;                       //update head of list
}


My question is - what happens to the value of h after it has been assigned to pointer temp->next? By my logic, when h is reassigned to temp, next should now point to temp by proxy?
But if it happened by my logic, this code would not create a linked list (which it does).
Is the value pointed to by next therefore static?
Well, h is assigned to temp but temp->next is not reassigned to h, when you write temp->next=h; it makes temp->next point to the value pointed by h, not to h itself.
Thanks for the rapid reply!
How is it that a dereference operator is not used in this case? e.g.
temp->next = *h;
rather than temp->next=h; ?
the arrow only deref's the lvalue, no?
Last edited on
Since "next" is a pointer, dereferencing h when assigning it would not be correct.
Here is a simplified version of it.
1
2
3
4
int A=6;
int* ptrToA,secondPtr;
ptrToA=&A;
secondPtr=*ptrToA;

As you can see, this is wrong since it is similar to:
secondPtr=6;
This had been bugging me for days. Thanks for the explanation. Makes perfect sense now.
Topic archived. No new replies allowed.