how to allocate an array on the heap and stack? Create a constructor and a destructor if it's needed.
Please provide example code in C++.
array allocation on stack is done when the array is declared
with specified size in the program itself before compilation but
not dynamically i.e if the compiler knows then it will allocate
memory in stack. Otherwise the programmer can allocate dynamically
or can force the memory allocation in heap by using "new"
operator.
Example :-
#include <iostream>
using namespace std;
class example{
public:
int *arr_heap;
example(){
//allocation in heap memory
arr_heap = new int[10];
cout<<"heap allocation"<<endl;
}
~example(){
//de-allocation in heap memory
free(arr_heap);
cout<<"heap de-allocated"<<endl;
}
};
int main() {
int arr_stack[10]; //de-allocation in stack memory
example obj;
}
Get Answers For Free
Most questions answered within 1 hours.