gpt4 book ai didi

c - 将链表数组传递给函数

转载 作者:行者123 更新时间:2023-11-30 15:28:22 26 4
gpt4 key购买 nike

我正在处理一个利用链表数组的等待列表。我以前使用过链表,但不知道如何将数组传递给函数。我首先声明了头指针和尾指针的数组。我收到此错误:

warning: incompatible pointer types passing 'struct node *(*)[4]'
to parameter of type 'struct node ***' [-Wincompatible-pointer-types]
add(&head,&tail);
^~~~~
lab6.c:10:31: note: passing argument to parameter 'tail' here
void add(NODE ***head,NODE ***tail);

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NODE struct node
struct node {
char name[20];
int number;
NODE *next;
};
void add(NODE ***head,NODE ***tail);
void delete(NODE ***head,NODE ***tail);
void show(NODE ***head);

int main() {
//Initialize
NODE *head[4]={NULL,NULL,NULL,NULL};
NODE *tail[4]={NULL,NULL,NULL,NULL};
int whileLoop=0;
while(whileLoop==0) {
int selection;
printf("Choose an Option: 1)Add new party 2)Remove table 3)Show list 4)Quit: ");
scanf("%d",&selection);

switch(selection) {
case 1:
add(&head,&tail);
break;
case 2:
delete(&head,&tail);
break;
case 3:
show(&head);
break;
case 4:
whileLoop=1;
break;
default:
add(&head,&tail);
}
}
return 0;
}
void add(NODE ***head,NODE ***tail) {
char tempName[20];
printf("enter a name for the party: ");
scanf("%s",tempName);
printf("enter a party size: ");
int tempSize;
scanf("%d",&tempSize);
if (tempSize>0) {
NODE *ptr=(NODE *)malloc(sizeof(NODE));
strcpy(ptr->name,tempName);
ptr->number=tempSize;
ptr->next=NULL;
int i;
if (tempSize>=1 && tempSize<=2) {
i=0;
} else if (tempSize>=3 && tempSize<=4) {
i=1;
} else if (tempSize>=5 && tempSize<=6) {
i=2;
} else {
i=3;
}
if (NULL==*head[i]) {
*head[i]=*tail[i]=ptr;
} else {
(*tail[i])->next=ptr;
(*tail[i])=ptr;
}
} else {
printf("Valid size not entered");
}



}
void delete(NODE ***head,NODE ***tail) {


}
void show(NODE ***head) {


}

最佳答案

您有指向节点的指针数组,当作为参数传递时,它将衰减为指向节点的指针。您在数组条目(列表的头部和尾部)中所做的更改将是永久性的。

所以你的函数的签名是:

void add(NODE **head, NODE **tail);

对于此客户端代码:

NODE *head[4] = {NULL, NULL, NULL, NULL};
NODE *tail[4] = {NULL, NULL, NULL, NULL};

add(head, tail);

add 中,将列表的头寻址为 head[i]

关于c - 将链表数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26626718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com