Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int *array = new int[n]; what is this function actually doing?

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?

like image 787
pauliwago Avatar asked Apr 25 '11 08:04

pauliwago


People also ask

What does int * array mean?

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.

What does new int [] do?

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 array [] and int [] array?

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.

What is the difference between int arr 5 ]; and int ARR 5 {};?

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.


2 Answers

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; 
like image 164
ANisus Avatar answered Sep 18 '22 13:09

ANisus


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).

like image 29
Nawaz Avatar answered Sep 19 '22 13:09

Nawaz