问题描述
我想将 B int 数组指针传递给 func 函数,并能够从那里更改它,然后查看 main 函数中的更改
I want to pass the B int array pointer into func function and be able to change it from there and then view the changes in main function
#include <stdio.h>
int func(int *B[10]){
}
int main(void){
int *B[10];
func(&B);
return 0;
}
上面的代码给了我一些错误:
the above code gives me some errors:
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
.只需删除 *
,
B
is a pointer to int
, thus B[0]
is an int
, and you can't dereference an int
. Just remove the *
,
int func(int *B){
B[0] = 5;
}
它有效.
在初始化中
int B[10] = {NULL};
您正在使用 void*
(NULL
) 初始化 int
.由于存在从 void*
到 int
的有效转换,这是有效的,但它并不完全符合,因为转换是实现定义的,并且通常由程序员,因此编译器会对此发出警告.
you are initialising anint
with a void*
(NULL
). Since there is a valid conversion from void*
to int
, that works, but it is not quite kosher, because the conversion is implementation defined, and usually indicates a mistake by the programmer, hence the compiler warns about it.
int B[10] = {0};
是 0 初始化 int[10]
的正确方法.
is the proper way to 0-initialise an int[10]
.
这篇关于C将int数组指针作为参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!