在C中传递和更改数组里面的数组 [英] Pass and change array inside function in C
问题描述
我有这个简单的C程序,它将函数内的任何数组元素更改为2。虽然它起作用,但让我困惑的是不应该将数组地址传递给函数,而不是数组本身?它不是这样工作的......
void function(int * val,int element){
*( val + element)= 2;
int main(int argc,char * argv [])
{
int value [2];
值[0] = 10;
值[1] = 5;
int element = 0;
function(value,element);
返回0;
val
)放入一个函数中,它衰变成指向数组的第一个元素的指针。
数组地址(& val
)指向与<$ c完全相同的地址$ c> val 但具有不同的类型 - 具有整个数组大小的类型。
在这里,您需要通过只是 val
。
I have this simple C program, which changes any array element to 2 inside a function. Although it works, what confuses me is that shouldn't I be passing the array address to the function, instead of the array itself? It's not been working that way...
void function(int *val, int element){
*(val+element) = 2;
}
int main(int argc, char *argv[])
{
int value[2];
value[0] = 10;
value[1] = 5;
int element = 0;
function(value, element);
return 0;
}
When you pass an array (val
) into a function, it decays into a pointer to the first element of the array.
The address of the array (&val
) points to the exact same address as that of val
but has a different type - a type that has the size of the entire array.
Here, you are required to pass just val
.
这篇关于在C中传递和更改数组里面的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!