+ 1
Arrays and Dynamic Memory
We have (int arr[]), which can have infinite elements, and increases the size of the array for every element that is added. We also have (int *arr = new int[]). Please correct me if I'm wrong. Could someone please explain the difference between these? I know the second one is dynamic due to keyword new, but the first one also appears dynamic. Many thanks đ
2 Answers
+ 3
kinda right and wrong. an array can essentially have infinite elements but it's not good practice. however the size of an array remains constant once it's declared meaning it can not be added to. int *arr=new int [] is another way to declare an array of ints (keep in mind that an array by definition is a pointer) the reason why this is done, or at last why I would do it, is because before c++11 or c++14 I forget which, you couldn't have something like:
int x;
cin>> x;
int myArr [x];
this would throw you an error. so if I wanted to create an array but didn't know the number of elements I wanted in it you could either make a vector which was usually more complicated than required. or we could do:
int x;
cin >> x;
int *myArr=new int [x]; this will dynamically set aside the amount f memory needed and create the array of x elements
+ 1
I see now. Many thanksđ