0
votes
struct my_struct
{
    struct my_struct *next;
    int data;
};

struct my_struct *root;

Then if I want to do something like find the struct in the linked list with the highest data value should I use my pointers like this?

struct my_struct *temp = head;
struct my_struct *highest = head;

for(I = 0; I<10; I++)
{
  temp = temp->next;
}

So my main question is: should it be temp = temp->next; or should it be temp = address of temp->next, temp = &temp->next; or should it be temp = *temp->next; and the logic behind it would help me a lot.

1
Try all these variants and see which ones the compiler is happy with. Is there more than one? - n. 1.8e9-where's-my-share m.
Compiler seems to be happy with the one I wrote in the code block. temp = temp->next; I would like to know though and although I been reading most of the posts here I still don't get it. I mean I know what & does and *pointer mean but I am still lost. - Mike John
Step through the code with a debugger. - Jabberwocky

1 Answers

1
votes

It should be temp = temp->next;

In c, the syntax temp->next is equivalent to (*temp).next. In other words, it dereferences the pointer temp and extracts the next attribute. You have defined the next attribute as a my_struct* (pointer to a my_struct). This is the same data type as temp, so the assignment works.

Also, I wouldn't recommend using a for loop with a fixed iteration limit--not unless you already know that the list will only ever have at most 10 elements. And in that case, why not use an array?

Try a loop like this:

struct my_struct* temp = head;
struct my_struct* highest = null;
int highestFound = -1; // or some other value known to be below all values in the list
while (temp != null) {
    if(temp->data > highestFound) {
        highestFound = temp->data;
        highest = temp;
    }
    temp = temp->next;
}