macawm wrote:
Hi all,
What is the difference between these two statements?
int* a = new int[8]
a is a pointer that is initialized with the address
of a dynamically allocated array of 8 ints.
and
int a[8];
a is an ARRAY of 8 ints (allocated wherever this statement
appears).
The reason I ask is because this
int len = sizeof(a) / sizeof(*a)
works for the second construct, but not the first.
Pointers are not arrays nor vice versa.
The size of a pointer is the same regardless of what value
you set it to and is unrelated to the size of the thing
it points to.
An array however, has a size that is the number of elements
in the array times the size of each element. Hence your
length test works fine to reverse that.
Pointers only really have the concept of pointing to one
thing. If you dynamically allocate an array, you'll have
to remember the size. Alternatively (and this is almost
certainly a better idea), use the standard vector class.
vector<int> a(8);
You can do things like:
a[3]
and you can ask the size by
a.size()
and you can size it with a variable (arrays only work with constant
sizes) and even resize it. You further don't have to remember
to free it or do special things when copying like you would for
dynamic allocations.