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

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

c++ - Array Assignment

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...