Error: Constant expression required, while declaring the array, like a[n]

Here, constant expression is required, means can we not take firstly the input of n and then declare the array like int a[n].

My code is:
#include <stdio.h>
int main() {

int n;

scanf("\n Enter the no. of elements of the array. %d", n);

int a[n];

for(int i=0; i<n; i++)

    scanf("\n Enter the elements of the array. %d", &a[i]);

for(int j=0; j<n; j++)

    printf(" %d", a[j]);

return 0;

}

Please also tell me is it a dynamic memory allocation? If yes, then how is it different from new. As both new also allocates memory at runtime and this also.

It is illegal to use a variable as an array size. So you must declare the size of your array according to your needs. You can also use vector as an alternative. Vectors use dynamic memory allocation and saves a lot of space when input size is less.

1 Like

Its a static allocation . Static arrays are created on stack and should give fixed size and de-allocated as end of the scope
Dynamic arrays are created on heap and can have variable length , and need to de-allocate .

#include <stdio.h>
#include<malloc.h>
int main()

{

int n;

printf(“Enter the no. of elements of the array”);

scanf("%d", &n);

//int *a=new int[n];

int *a = (int *) malloc(n * sizeof(int));

for(int i=0; i < n; i++)

{

printf(" Enter the elements of the array. ");

scanf("%d", &a[i]);

}

for(int j=0 ; j < n ; j++)

{

printf(" %d", a[j]);

}

//delete[] array;

free(a);

return 0;

}

1 Like

@optimus :-
First you need to understand the syntax of malloc
void* malloc (size_t size)
returning returning a pointer to the beginning of the block.

the type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable…

What is the meaning of int before malloc?

if you mean the int in parenthesis, that is a cast and its used to cast the “void” pointer to an int, so that the compiler knows that the first location in memory to which it will point to, will be an array of integers allocated dynamically