0

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;
}
user3424140
  • 3
  • 1
  • 3

1 Answers1

3

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.

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34