C中传递int数组指针作为参数成函数 [英] C pass int array pointer as parameter into a function
问题描述
我想通过对B int数组指针进入FUNC功能,并能够从那里改,然后查看在主要功能的变化
的#include<&stdio.h中GT;INT FUNC(中间体* B [10]){}诠释主要(无效){ 为int * B〔10〕; FUNC(蓝调); 返回0;
}
以上code给我一些错误:
在函数'主':|
警告:传递从兼容的指针类型'功能'参数1 [默认启用] |
注意:预期'诠释**,但参数的类型为INT *(*)[10]|
编辑:
新的code:
的#include<&stdio.h中GT;INT FUNC(INT * B){
* B [0] = 5;
}诠释主要(无效){ INT B〔10] = {NULL};
的printf(B [0] =%d个\\ n \\ n,B [0]);
FUNC(B)
的printf(B [0] =%d个\\ n \\ n,B [0]); 返回0;
}
现在我得到这些错误:
||在功能上FUNC:|
| 4 |错误:一元的无效类型参数'*'(有'诠释')|
||在函数'主':|
| 9 |警告:初始化将指针整数,未作施放[默认启用] |
| 9 |警告:(近初始化为'B [0]')[默认启用] |
|| ===构建完成:1错误,2警告=== |
在新的code,
INT FUNC(INT * B){
* B [0] = 5;
}
B
是一个指向 INT
,从而 B [0]
是 INT
,你可以不取消引用一个 INT
。只是删除 *
,
INT FUNC(INT * B){
B [0] = 5;
}
和它的作品。
在初始化
INT B〔10] = {NULL};
你是初始化一个 INT
与无效*
( NULL
)。由于没有从无效*
到 INT
的有效转换,这样的作品,但它是不是很洁净的,因为转换是实现定义,通常由程序员显示一个错误,因此编译器警告一下。
INT B〔10] = {0};
是有道0初始化一个 INT [10]
。
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]'|
EDIT: new code:
#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;
}
now i get these errors:
||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 ===|
In your new code,
int func(int *B){
*B[0] = 5;
}
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;
}
and it works.
In the initialisation
int B[10] = {NULL};
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};
is the proper way to 0-initialise an int[10]
.
这篇关于C中传递int数组指针作为参数成函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!