gpt4 book ai didi

C将int数组指针作为参数传递给函数

转载 作者:太空狗 更新时间:2023-10-29 16:23:42 26 4
gpt4 key购买 nike

我想将 B int 数组指针传递给 func 函数,并能够从那里更改它,然后在 main 函数中查看更改

#include <stdio.h>

int func(int *B[10]){

}

int main(void){

int *B[10];

func(&B);

return 0;
}

上面的代码给了我一些错误:

In function 'main':|
warning: passing argument 1 of 'func' from incompatible pointer type [enabled by default]|
note: expected 'int **' but argument is of type 'int * (*)[10]'|

编辑:新代码:

#include <stdio.h>

int func(int *B){
*B[0] = 5;
}

int main(void){

int B[10] = {NULL};
printf("b[0] = %d\n\n", B[0]);
func(B);
printf("b[0] = %d\n\n", B[0]);

return 0;
}

现在我得到这些错误:

||In function 'func':|
|4|error: invalid type argument of unary '*' (have 'int')|
||In function 'main':|
|9|warning: initialization makes integer from pointer without a cast [enabled by default]|
|9|warning: (near initialization for 'B[0]') [enabled by default]|
||=== Build finished: 1 errors, 2 warnings ===|

最佳答案

在你的新代码中,

int func(int *B){
*B[0] = 5;
}

B 是指向 int 的指针,因此 B[0] 是一个 int,您可以不要取消引用 int。只需删除 *,

int func(int *B){
B[0] = 5;
}

而且有效。

初始化中

int B[10] = {NULL};

您正在使用 void* (NULL) 初始化一个int。因为存在从 void*int 的有效转换,所以它可以工作,但它不太符合标准,因为转换是实现定义的,通常表示错误程序员,因此编译器会发出警告。

int B[10] = {0};

是对 int[10] 进行 0 初始化的正确方法。

关于C将int数组指针作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13730786/

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