This question is about C++
I always thought that name of an array in C++ is only a pointer, so I thought that
int ar[10];
cout << sizeof(ar);
will give me the same as sizeof(int *)
. But it gives 40 - so it is real size of whole array. It also gives 40 when array size is given by variable:
int n = 10;
int ar[n]
I want to copy a class that contains an array. If it would be allocated with operator new
then I should manualy copy this array within a copy constructor. But how about constant sized arrays? Does class contains only a pointer to an array, or does it contains whole array? Is simple memcpy(...)
safe here?
EDIT: Another example:
int n;
cin >> n;
int ar[n];
cout << sizeof(ar);
and it prints n*4. I'm using g++ on linux.
I even tried this:
class Test {
public:
int ar[4];
};
and
Test a, b, c;
a.ar[0] = 10;
b = a;
memcpy(&c, &a, sizeof(a));
a.ar[0] = 20;
cout << "A: " << a.ar[0] << endl;
cout << "B: " << b.ar[0] << endl;
cout << "C: " << c.ar[0] << endl;
and it gives:
A: 20
B: 10
C: 10
So array is stored as a part of a class and can be copied with memcpy. But is it safe?