-2

I am still knew in learning c and i am facing the following problem.

I am trying to initialize and declare an array but it is giving me compilation error.

const   int a =2;
int x[a]={2};
inverted_index
  • 2,329
  • 21
  • 40
Sara Chatila
  • 101
  • 1
  • 8

2 Answers2

5

Variable length arrays cannot be initialized.

Assign the values after definition:

const int a = 2;
int x[a];
x[0] = 2;
2501
  • 25,460
  • 4
  • 47
  • 87
  • @adminXVII No, `a` is not a constant, it is merely defined with const. `x` is a variable length array. Please read: https://stackoverflow.com/questions/3025050/error-initializer-element-is-not-constant-when-trying-to-initialize-variable-w, and https://stackoverflow.com/questions/12343027/const-keyword-and-constant-expressions-in-c99-and-c11, and C11 6.6 Constant expressions, and 6.2.5.Types paragraph 23 – 2501 Feb 22 '16 at 08:03
  • @adminXVII No problem. Don't forget to check the tags on questions. – 2501 Feb 23 '16 at 12:09
1

By using macro you can do that

#include<stdio.h>
#define a 2
int main()
{
 int x[a]={2};
 //do something with array x
 return 0;
}