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
Dynamically allocated:
int * pointerArray = new int[10];
[BTW, this is a pointer to an array of 10 ints, NOT a pointer array]
Statically allocated (possibly on the stack):
int array[10];
Otherwise they are the same.
The main difference is that some operations that are allowed on pointers are not allowed on arrays.
The problem with understanding C/C++ arrays when coming from Java is that C/C++ distinguishes between the array variable and the memory used to store the array contents. Both concepts are important and distinct. In Java, you really just have a reference to an object that is an array.
You also need to understand that C/C++ has two ways of allocating memory. Memory can be allocated on the help or the stack. Java doesn't have this distinction.
In C and C++, an array variable is a pointer to the first element of the array. An array variable can exist on the heap or the stack, and so can the memory that contains its contents. And they can be difference. Your examples are int
arrays, so you can consider the array variable to be an int*
.
There are two differences between int *pointerArray = new int[10];
and int array[10];
:
The first difference is that the memory that contains the contents of the first array is allocated on the heap. The second array is more tricky. If array
is a local variable in a function then its contents are allocated on the stack, but if it is a member variable of a class then its contents are allocated wherever the containing object is allocated (heap or stack).
The second difference is that, as you've realised, the first array is dynamic: its size can be determined at run-time. The second array is fixed: the compiler must be able to determine its size at compile time.