gpt4 book ai didi

c - 从 C 中的另一个函数修改数组

转载 作者:太空狗 更新时间:2023-10-29 15:20:01 25 4
gpt4 key购买 nike

这是我的主要函数:

main(){

int *seats[50] = {0};
char x;

do{
printf("A-Add Reservation\tC-Cancel Reservation\n");
scanf("%c", &x);
} while(x != 'a' && x != 'c');

switch(x){
case 'a':
addRes(&seats);
break;
default:
break;
}
}

我正在尝试将 seats[] 传递给 addRes() 函数,以便我可以在 addRes() 中修改它。这是函数:

void addRes(int **seats[]){
int s, i, scount=0, j=0, k=0, yourseats[]={0};
printf("How many seats do you require? ");
scanf("%i\n", &s);
for(i=0;i<=sizeof(*seats);i++){
if(*seats[i] == 0)
scount++;
}
if(scount >= s){
for(i=0;i<=s;){
if(*seats[i] == 0){
yourseats[j]=i;
*seats[i]=1;
i++; j++;
}
else i++;
}
printf("Your seat numbers are: \n");
while(k < j){
printf("%i\n", yourseats[k]);
k++;
}
}
else {
printf("Sorry, there are not enough seats available.\n");
}
}

编译时出现警告:

Line 15 (*seats[i]=1;) Assignment makes pointer from integer without a cast.  
Line 53: (addRes(&seats);) Passing argument 1 of 'addRes' from incompatible pointer type.
Line 3: (void addRes(int ** seats[]){) Expected 'int ***' but argument is of type 'int *(*)[50]'.

在运行程序时它会到达

How many seats do you require?  

输入值后不执行任何操作。任何帮助将不胜感激!

最佳答案

在函数参数中声明int **seats[] == int ***seats,表示*seats[i]<的类型int* 并且您正在为其分配一个数字,这是不兼容的类型错误:

*seats[i] = 1; 
^ ^ int
|
int*

incompatible types

接下来在 addRes(&seats);

seats in array of pointer 它的类型如果int*[50] &seat数组的指针&seat的类型是int*(*)[50] 其中函数参数类型是int ***,所以再次输入不兼容的错误。
请注意,您还从编译器收到一条合理的错误消息:Expected 'int ***' but argument is of type 'int * (*)[50]'。

建议:

正如我在您的代码中看到的那样,您不会在函数 addRes() 中为 seats[i] 分配内存,因此据我了解您不需要将 seat[] 数组声明为指针数组,但您需要简单的 int 数组。

更改 main() 中的声明:

int *seats[50] = {0};

应该只是:

int seats[50] = {0};
// removed * before seats

接下来只需将 seats[] 数组的名称传递给 addRes() 函数,函数声明应该是

addRes(int* seats)

or addRes(int seats[])

它使您在函数 addRes() 中的工作变得非常简单,您可以将其元素作为 seats[i] 访问(并且无需使用额外的 * 运算符)。

数组长度:

代码中的另一个概念性问题是您使用 sizeof(*seats) 来了解数组的长度。这是不对的!因为在 addRes() 函数中 seats 不是一个数组而是一个指针,所以它会给你地址的大小(但不是数组长度)。
是的,为了通知 addRes() 函数中 seats[] 的大小,发送一个名为 length 的额外参数,所以最终将 addRes() 声明为以下(阅读评论):

void addRes(int seats[], int length){
// access seat as
// seat[i] = 10;
// where i < length
}

按如下方式从 main() 调用此函数:

addRes(seats, 50);
// no need to use &

还有一个问题,您目前没有遇到,但在您运行代码时很快就会遇到,scanf() 需要在函数 addRes() 中额外输入 enter。要解决它,请更改:scanf("%i\n", &s); as scanf("%i", &s); 不需要额外的 \n 在 scanf() 中的格式字符串中。

关于c - 从 C 中的另一个函数修改数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772350/

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