Passing an array as an argument to a function in C

后端 未结 10 1231
太阳男子
太阳男子 2020-11-22 06:03

I wrote a function containing array as argument, and call it by passing value of array as follows.

void arraytest(int a[])
{
    // changed the array a
    a         


        
10条回答
  •  情歌与酒
    2020-11-22 06:26

    In C, except for a few special cases, an array reference always "decays" to a pointer to the first element of the array. Therefore, it isn't possible to pass an array "by value". An array in a function call will be passed to the function as a pointer, which is analogous to passing the array by reference.

    EDIT: There are three such special cases where an array does not decay to a pointer to it's first element:

    1. sizeof a is not the same as sizeof (&a[0]).
    2. &a is not the same as &(&a[0]) (and not quite the same as &a[0]).
    3. char b[] = "foo" is not the same as char b[] = &("foo").

提交回复
热议问题