Explain in your logbook the difference between dynamically a

Explain in your logbook the difference between dynamically allocating an array and statically declaring its size. How do you decide which technique to use on a case-by-case basis?

Solution

Statically allocating an array means to allocate memory to a fixed sized array in a function\'s stack frame(It is nothing but a part of memory implemented as stack for the function). Each function has it\'s own stack frame in memory which includes local variables of that function. Taking C++ programs as example:

int main() {

int arr[10];

return 0;

}

This program contains a function \'main\'. Function \'main\' has its own stack frame in memory. The statement int arr[10]; declares an array of 10 integers in main\'s stack frame. This is static allocation and we use it when we already know the size of an array, as the size that we can specify in this case is a constant (and not variable).

Whereas, in dynamic allocation of an array, array is stored in the heap location of memory(it\'s not related to data structure heap). In this type of allocation we can provide a variable as a size of an array. It is used in situations where size of array is decided at run-time of the programs. However, keep in mind that memory is a limited resource and the heap can be exhausted.

int* arr;

int size;

cin>>size; // take in the size of an array

arr = new int[i]; // allocate the array dynamically using keyword new

//Note: you need to free the dynamically allocated memory yourself, in order to use it again
//In constrast, see how in stack frame of a function statically allocated variables relieve memory after the function //scope ends

//use the arr and after it has no use relieve it memory

delete[] arr; // free the memory allocated by arr using delete operator

 Explain in your logbook the difference between dynamically allocating an array and statically declaring its size. How do you decide which technique to use on a

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site