简体   繁体   中英

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.

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 (eg int arr[25] = {0}; ) or dynamically allocated array (eg with calloc that zero initializes).

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM