You can't allocate an array of an unknown size.
So you need to allocate it dynamically "at run-time".
you can make this allocation using "new" in C++ or "malloc" in C.
For example:
In C++ if you want to allocate an array of an unknown size you should do the following:
int* v_X_array = new int[x];
int i;
for (i=0; i<x; i++)
{
v_X_array[i] = i;
}
The reason that we use integer pointer is that "new" returns the base address of the array "the address of the first element", so the only thing that can store addresses is pointers.
In C if you want to allocate an array of an unknown size you should do the following:
int* v_X_array = (int*) malloc(x*sizeof(int));
int i;
for(i=0; i<x; i++)
{
v_X_array[i] = i;
}
The malloc
function takes a single argument which specifies the number of bytes to be allocated and returns a void pointer so the casting (int*) is required.
For more explanations, look at the next section:
If we need to allocate an array of 20 integers it could be as follow: "malloc(20*sizeof(int))" where 20 is the number of allocated elements and sizeof(int) is the size of the type you want to allocate. If successful it returns a pointer to memory allocated. If it fails, it returns a null pointer.
Enter image description here