I have structure in C which looks like:
typedef struct node {
int id;
int salary;
struct node *next;
char name[30];
char phone[10];
char position[30];
} List;
I also have two variables List type and I want to sort the structures by id (the largest id will be last). My idea how to resolve this:
- Do **pointer point on *head (*head = pointer on first member of List).
- Check if **pointer.id larger then **pointer.next.id If yes -> **pointer.next will point on *pointer.next.next **pointer.next.next will point on &pointer
Here is code of solving this problem (I will do "cosmetics" of code and bubble sort algorithm after. Firstable just want to build code which will be work):
void sort(List head) {
int length = getListLength(head);
List **currentNode = &head;
for(int i = 0; i < length; i++) {
**currentNode = &head;
for(int j = 0; j < length; j++) {
if(currentNode->id > currentNode->next->id) {
currentNode->next = currentNode->next->next;
currentNode->next->next = ¤tNode;
}
}
}
}
There is errors:
^ ~~~~~
list.c:92:19: error: assigning to 'List' (aka 'struct node') from incompatible type 'List *' (aka 'struct node *'); remove &
**currentNode = &head;
^ ~~~~~
list.c:94:21: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
if(currentNode->id > currentNode->next->id) {
~~~~~~~~~~~^ ~~
list.c:94:39: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
if(currentNode->id > currentNode->next->id) {
~~~~~~~~~~~^ ~~~~
list.c:95:20: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
currentNode->next = currentNode->next->next;
~~~~~~~~~~~^ ~~~~
list.c:95:40: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
currentNode->next = currentNode->next->next;
~~~~~~~~~~~^ ~~~~
list.c:96:20: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
currentNode->next->next = ¤tNode;
~~~~~~~~~~~^ ~~~~
Please give me some way to fix this (without solving the problem. Just want to know what is wrong in my code and then fix it by myself).
Main function:
int main() {
List *head = (List *) malloc(sizeof(List));
if(head == NULL) {
return 1;
}
head -> id = 332513075;
head -> salary = 1000;
strcpy(head -> name, "Name Lastname");
strcpy(head -> phone, "0587885238");
strcpy(head -> position, "cleaner");
head -> next = (List *) malloc(sizeof(List));
head -> next->id = 2;
head -> next->salary = 2000;
strcpy(head -> next -> name, "Another name");
strcpy(head -> next -> phone, "1234567890");
strcpy(head -> next -> position, "CEO");
head -> next -> next = NULL;
sort(*head);
print_list(*head);
return 0;
}