C 如何对结构进行排序
我有C语言的结构,它看起来像:C 如何对结构进行排序,c,sorting,pointers,struct,C,Sorting,Pointers,Struct,我有C语言的结构,它看起来像: typedef struct node { int id; int salary; struct node *next; char name[30]; char phone[10]; char position[30]; } List; 我还有两个变量列表类型,我想按id对结构进行排序(最大的id将是最后一个)。 我的想法是如何解决这个问题: Do**指针指向*头(*头=列表第一个成员上的指针) 检查**pointer.id是否大于**p
typedef struct node {
int id;
int salary;
struct node *next;
char name[30];
char phone[10];
char position[30];
} List;
我还有两个变量列表类型,我想按id对结构进行排序(最大的id将是最后一个)。
我的想法是如何解决这个问题:
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;
}
- 第一个错误:
是一个头
,因此列表
将是一个头
;但您正试图将其分配到列表*
列表**
- 其他原因是将
视为一个currentNode
列表*
因此,将
currentNode
声明为列表*
将解决列出的错误。我认为您需要进行以下修改:
为什么是双指针**currentNode=&head立即修复是
List*currentNode=&head
但是我可以看到很多原因说明这个代码不起作用。@rootkonda因为head是第一个结构上的指针。@BalmainVuittonhead
在您发布的代码中不是指针。@BalmainVuitton我可以看到,为什么不将head作为指针传递给排序
和打印列表
函数呢?这是正常的做法。
^ ~~~~~
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;
~~~~~~~~~~~^ ~~~~
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;
}