I created a doubly linked list and in the function that adds values to the list, it calls the function list_next which is supposed to return the next node in the list but I'm unable to figure out just how to do that. I feel like ListPos Pos is a double pointer hence why I wrote my code like that, but it's apparently wrong. How should I go about writing it and how would I avoid that mistake in the future?
struct node
{
struct node *next;
struct node *prev;
char *value;
};
typedef struct list_pos
{
struct node *node;
} ListPos;
ListPos list_next(ListPos pos)
{
return &(*pos.node)->next;
}
CodePudding user response:
&(*pos.node)->next doesn't make any sense.
You probably want this:
ListPos list_next(ListPos pos)
{
ListPos next;
next.node = pos.node->next;
return next;
}
CodePudding user response:
Here's your code with some changes, explained in comments, which hopefully will help you:
struct node
{
struct node *next;
struct node *prev;
char *value;
};
// typedefs are more confusing than they are useful
struct list_pos
{
struct node *node;
};
struct list_pos list_next(struct list_pos pos)
{
// don't be afraid to use temp variables to make your code clearer
struct node *current = pos.node;
assert(current != NULL); // one way to indicate assumption
// you could also check if current is NULL and return NULL in that case
struct node *next = current->next;
return (struct list_pos){next}; // compound literal to avoid temp variable
}
CodePudding user response:
What Jabberwocky suggested is the right answer. I just wanted to add that you could replace
typedef struct list_pos
{
struct node *node;
} ListPos;
with
typedef struct node* ListPos;
because you looked like you were thinking that ListPos is a pointer rather than separate struct.
