2
#include<stdio.h>

main() {
  int a=5;
  int array[a]={0};
  printf("Success\n");
}

when i am executing the program it will through a error as

b.c: In function ‘main’:
b.c:8:1: error: variable-sized object may not be initialized
b.c:8:1: warning: excess elements in array initializer [enabled by default]
b.c:8:1: warning: (near initialization for ‘array’) [enabled by default]

In cc complier . but i can assign like this

 int array[5]={0};

If anyone correct me?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Bhuvanesh
  • 1,269
  • 1
  • 15
  • 25

3 Answers3

4

This statement

int array[a]={0};

declares a Variable Length Array (VLA).

According to C Standard (6.7.9 Initialization)

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.

The problem is that the compiler shall know the array size at compile time that to generate the code that initialize an array.

Consider an example

void f( size_t n )
{
    int a[n] = { 1, 2, 3, 4, 5 };
    //...
}

Here is a is a variable length array. Now as n can have any value then the number of initializers in the array definition can be greater than the size of the array. So this code breaks the Standard from another side because the number of initializers may not be greater than the number of elements of array. On the other hand if the number of initializers less than the number of elements of array then what to do in this case? Maybe the programmer did not mean that some elements shall be zero-initialized.

As for this declaration

int array[5]={0};

then there is no variable length array. The size of the array is known at compile time. So there is no problem

.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

"Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++"

says here.

Compilers can differ in some situations. It's normal to have problems with variable-sized arrays. This should work if you really need to do this

#include<stdio.h>
#DEFINE A 5

 main()
 {
 int array[A]={0};
 printf("Success\n");
 }
Emre Acar
  • 920
  • 9
  • 24
0

The elements field within square brackets [], representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs.

Akhilesh Jaiswal
  • 227
  • 2
  • 14