Array Assignment

前端 未结 3 1393
心在旅途
心在旅途 2020-12-19 14:47

Let me explain with an example -

#include 

void foo( int a[2], int b[2] ) // I understand that, compiler doesn\'t bother about the
                  


        
相关标签:
3条回答
  • 2020-12-19 15:05

    You answered your own question.

    Because these

    int a[] = { 1,2 };
    int b[] = { 3,4 };
    

    have type of int[2]. But these

    void foo( int a[2], int b[2] )
    

    have type of int*.

    You can copy pointers but cannot copy arrays.

    0 讨论(0)
  • 2020-12-19 15:10

    The answer is in the concept "pass by value", which means that the called function receives copies of the arguments -- which are pointers to ints. So a and b are local copies of those pointers (which don't exist in the caller; they were the results of conversions from the arrays, that is, the addresses of their first elements). It would be no different if you wrote

    void foo( int aparam[2], int bparam[2] )
    {
        int* a = aparam;
        int* b = bparam;
    
        a = b ;
    }
    

    Dennis Ritchie has acknowledged that the array syntax for parameters is a wart on the language, and was only there to ease conversion of B programs -- ancient history! It also had a deleterious effect on the design of C++, because arrays cannot be passed by value. This syntax is a constant source of confusion. So ... don't use it; pretend it's not legal. If everyone does that, it can fade away and maybe in a few decades can be given proper semantics.

    Update: For more information on call-by-value (the only form of call in C and Java; see my comments below), call-by-reference (added in C++), and other evaluation strategies, see http://en.wikipedia.org/wiki/Evaluation_strategy

    0 讨论(0)
  • 2020-12-19 15:16

    In the main function
    a and b are constant pointers actually they are the address of the first elements. They are like l-value. you cannot copy to l-value but you can change the value of the integers they point to.

    In the foo function
    a and b are pointers. so you can change their values.

    0 讨论(0)
提交回复
热议问题