Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we can directly copy pointers, but we can not directly copy arrays in c++

Tags:

c++

Theorem says that we cannot initialize an array as a copy of another array. But we can initialize pointer as a copy of pointer that points to the first element of another array:

int a[] = {0, 1, 2}; 
int a2[] = a;       //error
int *a3 = a;        //OK

Why int a2[] = a; is an error?

like image 957
vladinkoc Avatar asked Oct 15 '12 13:10

vladinkoc


2 Answers

Arrays can't be assigned to or initialized from another array object in C++ because they can't in C, and they can't in C for historical reasons that aren't really relevant any more.

In very early proto-C, there would have be some confusion whether an assignment like int a[] = {0}; int b[] = {0}; a = b; should copy the contents of array b to a, or re-seat the name a to refer to b. Likewise with initialization, whether a should be a copy of b or an alias. This ambiguity hasn't existed for 40 years: it soon became clear that if it were to be allowed then the sensible meaning in C (and C++) would be that it should copy, but arrays in C were never made into "proper" value types.

There's no technical reason why it's impossible, and for example you can assign a struct type that has an array as a data member. The standard simply doesn't define your code to be correct C++.

The behavior of pointers isn't directly relevant to this. Initializing a pointer (to point to the first element of an array) is a different operation from initializing an array and its contents, and the language allows different things on the RHS.

like image 140
Steve Jessop Avatar answered Oct 12 '22 23:10

Steve Jessop


Arrays are not pointers, so you can't expect to use them like pointers without running into trouble. Visit https://blogs.oracle.com/ksplice/entry/the_ksplice_pointer_challenge for an activity that will help you learn the difference.

You can initialize an array as a copy of another array if you wrap the array in a struct.

struct myarray {
  int a[3];
};

If your compiler allows GNU C++ style designated initializers:

myarray a = {a: {0, 1, 2}};

This does a copy of the struct, including a's array to a2's array.

myarray a2 = a;

The arrays will be at different places in memory:

bool is_different_array = a2.a != a.a; // true
like image 24
Patater Avatar answered Oct 13 '22 01:10

Patater