Something in the while loop is giving me this error. I can't figure out what to look up because this error seems way to common to find out what to do with my specific example
#include <stdlib.h>
#include <stdio.h>
/*Structure declarations*/
struct Data {
int id_number;
float ratings;
};
typedef struct Node{
struct Data player;
struct Node *next;
}Node;
/*function declaration*/
void push(struct Node *list_head, int unique_id, float grade);
int main(){
/* Initialize list_head to Null since list is empty at first */
Node *list_head = NULL;
Node *traversalPtr;
push(list_head, 1, 4.0);
push(list_head, 2, 3.87);
push(list_head, 3, 3.60);
traversalPtr = list_head;
while(traversalPtr -> next != NULL){
printf("%d\n",traversalPtr -> player.id_number);
traversalPtr = traversalPtr -> next;
}
}
...function declarations
The problem is that the function
void push(struct Node *list_head, int unique_id, float grade);
deals with copies of original pointers defined in main because the pointers are passed by values.
You should declare the function like
void push(struct Node **list_head, int unique_id, float grade);
and call it like
push( &list_head, 1, 4.0 );
Here is an example of how the function can be defined (I assume that the function appends nodes to its tail).
int push(struct Node **list_head, int unique_id, float grade)
{
struct Node *node = malloc( sizeof( struct Node ) );
int success = node != NULL;
if ( success )
{
node->player.id_number = unique_id;
node->player.ratings = grade;
node->next = NULL;
while ( *list_head ) list_head = &( *list_head )->next;
*list_head = node;
}
return success;
}
Also this loop
traversalPtr = list_head;
while(traversalPtr -> next != NULL){
printf("%d\n",traversalPtr -> player.id_number);
traversalPtr = traversalPtr -> next;
}
is incorrect. It should look like
traversalPtr = list_head;
while(traversalPtr != NULL){
printf("%d\n",traversalPtr -> player.id_number);
traversalPtr = traversalPtr -> next;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.