I\'m familiar with Java and trying to teach myself C/C++. I\'m stealing some curriculum from a class that is hosting their materials here. I unfortunately can\'t ask the tea
My understanding is that an array in C is simply a reference to the memory address of the first element in the array.
So, what is the difference between int *pointerArray = new int[10]; and int array[10]; if any?
What you mention is the reason for much confusion in any C/C++ beginner.
In C/C++, an array corresponds to a block of memory sufficiently large to hold all of its elements. This is associated to the []
syntax, like in your example:
int array[10];
One feature of C/C++ is that you can refer to an array by using a pointer to its type. For this reason, you are allowed to write:
int* array_pointer = array;
which is the same as:
int* array_pointer = &array[0];
and this allows to access array elements in the usual way: array_pointer[3]
,
but you cannot treat array
as a pointer, like doing pointer arithmetics on it (i.e., array++ miserably fails).
That said, it is also true that you can manage arrays without using the []
syntax at all and just allocate arrays by using malloc
and then using them with raw pointers. This makes the "beauty" of C/C++.
Resuming: a distinction must be made between the pointer and the memory that it points to (the actual array):
the []
syntax in declarations (i.e., int array[10];
) refers to both aspects at once (it gives you, as to say, a pointer and an array);
when declaring a pointer variable (i.e., int* p;
), you just get the pointer;
when evaluating an expression (i.e., int i = p[4];
, or array[4];
), the []
just means dereferencing a pointer.
Apart from this, the only difference between int *pointerArray = new int[10];
and int array[10];
is that former is allocated dynamically, the latter on the stack.