[英]C - Trouble passing array reference to pointer argument in function
我无法将 integer 数组作为参考传递,然后修改原始数组。
#include <stdio.h>
// sets the 2 element of i to 5
void setToFive(int *i[10]){
*i[2] = 5;
printf("hello\n");
}
int main(){
int i[10];
setToFive(&i);
// confirm i[2] == 5
printf("%d\n", i[2]);
}
编译器抱怨无效类型
[vinessa@komputilo ch1]$ gcc test.c
test.c: In function ‘setToFive’:
test.c:5:5: error: invalid type argument of unary ‘*’ (have ‘int’)
5 | *i[2] = 5;
| ^~~~~
test.c: In function ‘main’:
test.c:11:15: warning: passing argument 1 of ‘setToFive’ from incompatible pointer type [-Wincompatible-pointer-types]
11 | setToFive(&i);
| ^~
| |
| int (*)[10]
test.c:4:21: note: expected ‘int *’ but argument is of type ‘int (*)[10]’
4 | void setToFive(int *i){
| ~~~~~^
分段故障
[vinessa@komputilo ch1]$ ./a.out
Segmentation fault (core dumped)
几个小时以来一直在努力解决问题,请帮忙。
给你
#include <stdio.h>
// sets the 2 element of i to 5
void setToFive(int *i){
i[2] = 5;
printf("hello\n");
}
int main(){
int i[10];
setToFive(i);
printf("%d\n", i[2]);
}
如果要更改数组的元素,只需按值传递即可。 在这种情况下,数组指示符被隐式转换为指向其第一个元素的指针。 使用指针和指针算法,您可以更改数组的任何元素。
事实上,在这种情况下,您通过指向它们的指针间接地通过引用传递数组元素。
注意这些 function 声明
void setToFive(int i[100]);
void setToFive(int i[10]);
void setToFive(int i[1]);
void setToFive(int i[]);
是等效的并且声明相同的一个 function 声明,编译器将其调整为以下声明
void setToFive(int *i);
这就是 function 处理指针的结果。
至于在这个 function 调用中用作参数的表达式
setToFive(&i);
那么它的类型为int ( * )[10]
因为指向的数组被声明为
int i[10];
它与我已经写过的参数int *i[10]
的类型不同,编译器将其调整为int **
类型。
您正在传递一个指向整数的指针数组,而不是整数数组。 您可以删除各种*
声明和运算符,并只需传递一个简单的数组作为参数(数组参数将衰减为指针):
#include <stdio.h>
// sets the 2 element of i to 5
void setToFive(int i[10])
{
i[2] = 5;
printf("hello\n");
}
int main()
{
int i[10];
setToFive(i);
// confirm i[2] == 5
printf("%d\n", i[2]);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.