Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable list array initialization in C explained [duplicate]

Tags:

c

Give an a basic set of C code:

int a = 5;
int b[a] = {1,2,3,4,5};

Why does this generate this error?

$gcc -o demo demo.c
error: variable-sized object may not be initialized

I understand that it is a bad thing to do and the compiler won't let you. However as a teacher I am having a hard time coming up with an explanation as to why you can not and should not do this.

(Assume C99)

How would you explain what is happening here?

like image 224
David Milanese Avatar asked Apr 08 '26 09:04

David Milanese


1 Answers

Why does this generate this error?

C standard doesn't allow this. Variable length arrays can't be initialized using brace-enclosed list of initializers.

Standard says:
C11-§6.7.9/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.

like image 92
haccks Avatar answered Apr 09 '26 22:04

haccks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!