I am confused about how to create a dynamic defined array:
int *array = new int[n];
I have no idea what this is doing. I can tell it's creating a pointer named array that's pointing to a new object/array int? Would someone care to explain?
It's an array of pointers to an integer. ( array size is 9 elements. Indexes: 0 - 8) This can also be stated as being an array of integer pointers. int array[9] , is an array of integers.
new int[] means initialize an array object named arr and has a given number of elements,you can choose any number you want,but it will be of the type declared yet.
What is the difference between int[] a and int a[] in Java? There is no difference in these two types of array declaration. There is no such difference in between these two types of array declaration. It's just what you prefer to use, both are integer type arrays.
int array [5] = {}; is a static allocation wherein an array of 5 integers is created on the stack and initialized to a default value (probably 0). Its type is “ array of 5 ints (int[5]) ”, and the variable array can only be an array of 5 ints. The array is ready to use as normal.
new allocates an amount of memory needed to store the object/array that you request. In this case n numbers of int.
The pointer will then store the address to this block of memory.
But be careful, this allocated block of memory will not be freed until you tell it so by writing
delete [] array;
int *array = new int[n];
It declares a pointer to a dynamic array of type int
and size n
.
A little more detailed answer: new
allocates memory of size equal to sizeof(int) * n
bytes and return the memory which is stored by the variable array
. Also, since the memory is dynamically allocated using new
, you should deallocate it manually by writing (when you don't need anymore, of course):
delete []array;
Otherwise, your program will leak memory of at least sizeof(int) * n
bytes (possibly more, depending on the allocation strategy used by the implementation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With