+ 3
it's so simple. you can create a dynamic array via pointers:
for example:
int* ptr = new int[3];
//and you free memory by using the delete keyword:
delete[] ptr;
here is the general syntax for creating dynamic arrays:
type* array = new type[size];
+ 7
Syntax
pointer_variable = new
data_type;
+ 2
When there is a possibility that size of array may change at runtime, then it is time to consider the use of STL dynamic collection, less hassle on your side ...
+ 1
Manav Roy it's not dependent on the user input
for your code this is the approach:
int* arr = new int[4];
arr[0]=2;
arr[1]=7;
arr[2]=6;
arr[3]=9;
//and at the end
delete[] arr;
you are using a dynamic array for some reason, right? we don't just manually use them, when you already know the array values why would you bother yourself with dynamic arrays when it can easily be done with automatic allocation?
And since it's a pointer that always by default points at the first element you can't assign multiple values to it.
+ 1
Manav Roy if you have to increase the array size here is the approach:
Allocate a new[] array and store it in a temporary pointer.
Copy over the previous values that you want to keep.
Delete[] the old array.
Change the member variables, ptr, and size to point to the new array and hold the new size.
remember we are talking about arrays in C++ not C and what I wrote above is the only way to use dynamic memory allocation or change the array size
+ 1
Ok Manav Roy. here is the code:
#include <iostream>
using namespace std;
int main() {
int* arr = new int[2];
arr[0]=1;
arr[1]=2;
int * new_array = new int[4];
for(int i = 0;i<2;i++)
{
new_array[i]=arr[i];
}
delete[]arr;
return 0;
}
+ 1
Hi, dynamic arrays are created on the heap. The very reason you want to have dynamic array is that you donât know the size of the array at compile time. you can use initializer list if you want to (e.g. int* arr = new int[3]{1, 2, 3};). In addition, using ânewâ can throw exception. So, itâs better to learn how to tackle that from the beginning.