Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Assignment

Tags:

c++

arrays

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.

like image 451
Mahesh Avatar asked Feb 25 '23 20:02

Mahesh


1 Answers

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.

like image 52
Yakov Galka Avatar answered Mar 07 '23 23:03

Yakov Galka