someone
someone

Reputation: 1696

Dynamic array initialization in c

According to C99 standards we can do this

int n = 0;
scanf("%d",&n);
int arr[n];

this is one of the way to create dynamic array in c. Now I want to initialize this array to 0 like this

int arr[n] = {0};

Here my compiler producing error. I want to know can we do this? Is it according to standard? At compile time we provide sufficient memory for arrays, but here it is unknown at compile time. How it is happening?

Upvotes: 0

Views: 1927

Answers (2)

user529758
user529758

Reputation:

can we do this?

No. But you can do this:

int arr[n];
memset(arr, 0, sizeof(arr));

You lose the syntactic sugar for initialization, but you get the functionality.    

Upvotes: 7

SANDEEP
SANDEEP

Reputation: 1082

int n = 0;
scanf("%d",&n);
int arr[n];

You can not do that. If you want allocate memory to an array then use the malloc or calloc functions.

Upvotes: 0

Related Questions