Reputation: 3
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;
}
Upvotes: 0
Views: 4605
Reputation: 11453
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
.
Upvotes: 3