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;
}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.