user13371678
user13371678

Reputation:

How do I declare a variable length array and initialize it to zero?

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

I want to initialize all elements to 0.

on compilation i get error "expected expression" at line 4 position 8.

I searched but found no method to do that.

Upvotes: 0

Views: 140

Answers (3)

John Bode
John Bode

Reputation: 123448

6.7.9 Initialization
...
Constraints
...
3     The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

C 2011 Online Draft

Emphasis added. VLAs may not have an initializer as part of their definition. You will have to zero out the array after the declaration, either using memset or a loop as shown by others.

Upvotes: 0

0___________
0___________

Reputation: 67476

instead of

arr[n]={0};

you need to (assuming automatic variables)

in definition (assuming n is a constant expression):

int arr[n] = {0,};

or after definition

memset(arr, 0, n * sizeof(*arr));

or

for(size_t i = 0; i < n; i++) arr[i] = 0;

if n is a constant expression and the arr has static storage duration (is global or has static keyword before it) you do not have to do anything

Upvotes: 0

P.P
P.P

Reputation: 121357

VLAs (variable length arrays) can't be initialized.

You can instead use memset:

memset(arr, 0, sizeof arr);

Alternatively, you can use a fixed size array (e.g. int arr[25] = {0};) or dynamically allocated array (e.g. with calloc that zero initializes).

Upvotes: 4

Related Questions