Passing an array as an argument to a function in C

后端 未结 10 1196
太阳男子
太阳男子 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:19

    Arrays in C are converted, in most of the cases, to a pointer to the first element of the array itself. And more in detail arrays passed into functions are always converted into pointers.

    Here a quote from K&R2nd:

    When an array name is passed to a function, what is passed is the location of the initial element. Within the called function, this argument is a local variable, and so an array name parameter is a pointer, that is, a variable containing an address.

    Writing:

    void arraytest(int a[])
    

    has the same meaning as writing:

    void arraytest(int *a)
    

    So despite you are not writing it explicitly it is as you are passing a pointer and so you are modifying the values in the main.

    For more I really suggest reading this.

    Moreover, you can find other answers on SO here

提交回复
热议问题