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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With