Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let me explain with an example -

#include <iostream>

void foo( int a[2], int b[2] ) // I understand that, compiler doesn't bother about the
                               // array index and converts them to int *a, int *b
{
    a = b ;  // At this point, how ever assignment operation is valid.

}

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

    foo( a, b );

    a = b; // Why is this invalid here.

    return 0;
}

Is it because, array decays to a pointer when passed to a function foo(..), assignment operation is possible. And in main, is it because they are of type int[] which invalidates the assignment operation. Doesn't a,b in both the cases mean the same ? Thanks.

Edit 1:

When I do it in a function foo, it's assigning the b's starting element location to a. So, thinking in terms of it, what made the language developers not do the same in main(). Want to know the reason.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
329 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...