Ошибка variable sized object may not be initialized

Why do I receive the error «Variable-sized object may not be initialized» with the following code?

int boardAux[length][length] = {{0}};

Spikatrix's user avatar

Spikatrix

20.2k7 gold badges37 silver badges82 bronze badges

asked Jun 21, 2010 at 7:52

helloWorld's user avatar

6

I am assuming that you are using a C99 compiler (with support for dynamically sized arrays). The problem in your code is that at the time when the compilers sees your variable declaration it cannot know how many elements there are in the array (I am also assuming here, from the compiler error that length is not a compile time constant).

You must manually initialize that array:

int boardAux[length][length];
memset( boardAux, 0, length*length*sizeof(int) );

answered Jun 21, 2010 at 8:06

David Rodríguez - dribeas's user avatar

5

You receive this error because in C language you are not allowed to use initializers with variable length arrays. The error message you are getting basically says it all.

6.7.8 Initialization

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

answered Jun 21, 2010 at 8:09

AnT stands with Russia's user avatar

6

This gives error:

int len;
scanf("%d",&len);
char str[len]="";

This also gives error:

int len=5;
char str[len]="";

But this works fine:

int len=5;
char str[len]; //so the problem lies with assignment not declaration

You need to put value in the following way:

str[0]='a';
str[1]='b'; //like that; and not like str="ab";

answered Nov 8, 2014 at 9:21

Amitesh Ranjan's user avatar

Amitesh RanjanAmitesh Ranjan

1,1621 gold badge12 silver badges9 bronze badges

After declaring the array

int boardAux[length][length];

the simplest way to assign the initial values as zero is using for loop, even if it may be a bit lengthy

int i, j;
for (i = 0; i<length; i++)
{
    for (j = 0; j<length; j++)
        boardAux[i][j] = 0;
}

answered Mar 27, 2016 at 12:35

Krishna Shrestha's user avatar

2

Variable length arrays are arrays whose length is not known by the compiler at compile time. In your case length is a variable. I conclude this, because if length was a e.g. preprocessor macro defined as a literal integer your initialization would work. The first C language standard from 1989 did not allow variable length arrays, they were added in 1999. Still the C standard does not allow these to be initialized with an expression like yours (although one could argue that it could or should allow it).

The best way to initialize a variable array is like this:

int boardAux[length][length];
memset( boardAux, 0, sizeof(boardAux) );

memset is a very fast standard library function for initializing memory (to 0 in the above case). sizeof(boardAux) returns the number of bytes occupied by boardAux. sizeof is always available but memset requires #include <string.h>. And yes — sizeof allows a variable sized object as argument.

Note that if you have a normal array (not variable length) and just want to initialize the memory to zero you never need nested brackets, you can initialize it simply like this:

struct whatEver name[13][25] = {0};

answered Sep 20, 2021 at 1:59

Oskar Enoksson's user avatar

The array is not initialized with the memory specified anf throws an error
variable sized array may not be initialised
I prefer usual way of initialization,

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

answered Sep 21, 2020 at 13:25

Keth's user avatar

KethKeth

413 bronze badges

2

The question is already answered but I wanted to point out another solution which is fast and works if length is not meant to be changed at run-time. Use macro #define before main() to define length and in main() your initialization will work:

#define length 10

int main()
{
    int boardAux[length][length] = {{0}};
}

Macros are run before the actual compilation and length will be a compile-time constant (as referred by David Rodríguez in his answer). It will actually substitute length with 10 before compilation.

answered Apr 12, 2020 at 21:42

Sergey's user avatar

2

int size=5;
int ar[size ]={O};

/* This  operation gives an error -  
variable sized array may not be 
initialised.  Then just try this. 
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
    ar[i]=0;
}

answered May 22, 2020 at 6:57

Codetheft's user avatar

1

Simply declare length to be a cons, if it is not then you should be allocating memory dynamically

answered Mar 2, 2016 at 20:26

Azizou's user avatar

4

Why do I receive the error «Variable-sized object may not be initialized» with the following code?

int boardAux[length][length] = {{0}};

Spikatrix's user avatar

Spikatrix

20.2k7 gold badges37 silver badges82 bronze badges

asked Jun 21, 2010 at 7:52

helloWorld's user avatar

6

I am assuming that you are using a C99 compiler (with support for dynamically sized arrays). The problem in your code is that at the time when the compilers sees your variable declaration it cannot know how many elements there are in the array (I am also assuming here, from the compiler error that length is not a compile time constant).

You must manually initialize that array:

int boardAux[length][length];
memset( boardAux, 0, length*length*sizeof(int) );

answered Jun 21, 2010 at 8:06

David Rodríguez - dribeas's user avatar

5

You receive this error because in C language you are not allowed to use initializers with variable length arrays. The error message you are getting basically says it all.

6.7.8 Initialization

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

answered Jun 21, 2010 at 8:09

AnT stands with Russia's user avatar

6

This gives error:

int len;
scanf("%d",&len);
char str[len]="";

This also gives error:

int len=5;
char str[len]="";

But this works fine:

int len=5;
char str[len]; //so the problem lies with assignment not declaration

You need to put value in the following way:

str[0]='a';
str[1]='b'; //like that; and not like str="ab";

answered Nov 8, 2014 at 9:21

Amitesh Ranjan's user avatar

Amitesh RanjanAmitesh Ranjan

1,1621 gold badge12 silver badges9 bronze badges

After declaring the array

int boardAux[length][length];

the simplest way to assign the initial values as zero is using for loop, even if it may be a bit lengthy

int i, j;
for (i = 0; i<length; i++)
{
    for (j = 0; j<length; j++)
        boardAux[i][j] = 0;
}

answered Mar 27, 2016 at 12:35

Krishna Shrestha's user avatar

2

Variable length arrays are arrays whose length is not known by the compiler at compile time. In your case length is a variable. I conclude this, because if length was a e.g. preprocessor macro defined as a literal integer your initialization would work. The first C language standard from 1989 did not allow variable length arrays, they were added in 1999. Still the C standard does not allow these to be initialized with an expression like yours (although one could argue that it could or should allow it).

The best way to initialize a variable array is like this:

int boardAux[length][length];
memset( boardAux, 0, sizeof(boardAux) );

memset is a very fast standard library function for initializing memory (to 0 in the above case). sizeof(boardAux) returns the number of bytes occupied by boardAux. sizeof is always available but memset requires #include <string.h>. And yes — sizeof allows a variable sized object as argument.

Note that if you have a normal array (not variable length) and just want to initialize the memory to zero you never need nested brackets, you can initialize it simply like this:

struct whatEver name[13][25] = {0};

answered Sep 20, 2021 at 1:59

Oskar Enoksson's user avatar

The array is not initialized with the memory specified anf throws an error
variable sized array may not be initialised
I prefer usual way of initialization,

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

answered Sep 21, 2020 at 13:25

Keth's user avatar

KethKeth

413 bronze badges

2

The question is already answered but I wanted to point out another solution which is fast and works if length is not meant to be changed at run-time. Use macro #define before main() to define length and in main() your initialization will work:

#define length 10

int main()
{
    int boardAux[length][length] = {{0}};
}

Macros are run before the actual compilation and length will be a compile-time constant (as referred by David Rodríguez in his answer). It will actually substitute length with 10 before compilation.

answered Apr 12, 2020 at 21:42

Sergey's user avatar

2

int size=5;
int ar[size ]={O};

/* This  operation gives an error -  
variable sized array may not be 
initialised.  Then just try this. 
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
    ar[i]=0;
}

answered May 22, 2020 at 6:57

Codetheft's user avatar

1

Simply declare length to be a cons, if it is not then you should be allocating memory dynamically

answered Mar 2, 2016 at 20:26

Azizou's user avatar

4

So this section of code generates a huge amount of errors but it works when I have InputM[3][3] = blah

Why would this be. For reference, code:

int n = 3;
printf("%ldn", n);
double InputM[n][n] = { { 2, 0, 1 }, { 3, 1, 2 }, { 5, 2, 5} };

Generates:

prog3.c: In function 'main':
prog3.c:47: error: variable-sized object may not be initialized
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM')

alk's user avatar

alk

69.6k10 gold badges104 silver badges254 bronze badges

asked Nov 7, 2013 at 11:31

SaltySeaDog's user avatar

1

Compile-time, you compiler does not know how many elements are in your matrix. In C, you can dynamically allocate memory using malloc.

You could use a define to create a constant value:

#define N 3

int main()
{
    double InputM[N][N] = { { 2, 0, 1 }, { 3, 1, 2 }, { 5, 2, 5} };
}

Or malloc:

int main()
{
    int n = 3;
    int idx;
    int row;
    int col;

    double **inputM;
    inputM = malloc(n * sizeof(double *));
    for (idx = 0; idx != n; ++idx)
    {
        inputM[idx] = malloc(n * sizeof(double));
    }

    // initialise all entries on 0
    for (row = 0; row != n; ++row)
    {
        for (row = 0; row != n; ++row)
        {
            inputM[row][col] = 0;
        }
    }

    // add some entries
    inputM[0][0] = 2;
    inputM[1][1] = 1;
    inputM[2][0] = 5;
}

answered Nov 7, 2013 at 11:33

Arjen's user avatar

ArjenArjen

6361 gold badge7 silver badges13 bronze badges

6

In C99, variable-sized array can’t be initialized, why ?

Because at the compile time, the compiler doesn’t know the exact size of array, so you cannot initialize it.

n will be evaluated at runtime, then your array will be allocated on the stack-frame.

answered Nov 7, 2013 at 11:36

linkdd's user avatar

linkddlinkdd

9951 gold badge9 silver badges24 bronze badges

  • Forum
  • Beginners
  • variable sized object may not be initial

variable sized object may not be initialized

I’m trying to let the user choose between three functions for the program to run, but when I compile I get the error» variable-sized object `addnumber’ may not be initialized» on line 47. My code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    //char b;
    cout << "Choose to find the average, square or add" << endl;
    string input;
    cin >> input;
    
    if (input== "Average")
    {
    
    double x;
    double y;
    double w; 
    double z;
	cout << "Enter numbers to be added" << endl;
	cin >> x; 
	cin >> y; 
	cin >> w;
	cin >> z;
	cout << "The average is: " << endl;
	cout << (x + y + w + z) / 4 << endl;
}
    else if (input== "Square")
    {
	double a;

	cout << "Enter number to be squared" << endl;
	cin >> a;
	cout << "Square is: " << a * (a) << endl;
}
    else if (input== "Add")
    {
         int c;
         double d;
         double e;
         double f;
         double g;
         double h;
         double i;
         double j;
         cout << "Enter how many numbers you want to add" << endl;
         cin >> c;
         double addnumber[c] = {d,e,f,g,h,i,j};
         cout << "Enter numbers to be added" << endl;
         
         if (c = 2)
         {
               cin >> d;
               cin >> e;
               cout << "Sum is: " << d + e << endl;
               }
         else if (c = 3)
         {
              cin >> d;
              cin >> e;
              cin >> f;
              cout << "Sum is: " << d + e + f << endl;
              }      
         else if (c = 4)
         {
              cin >> d;
              cin >> e;
              cin >> f;
              cin >> g;
              cout << "Sum is: " << d + e + f + g << endl;
              }     
         else if (c = 5)
         {
              cin >> d;
              cin >> e;
              cin >> f;
              cin >> g;
              cin >> h;
              cout << "Sum is: " << d + e + f + g + h << endl;
              } 
         else if (c = 6)
         {
              cin >> d;
              cin >> e;
              cin >> f;
              cin >> g;
              cin >> h;
              cin >> i;
              cout << "Sum is: " << d + e + f + g + h + i << endl;
              }    
         else if (c > 6)
         {
              cout << "Yo number is too big bro" << endl;
              }
         else 
         {
              cout << "Yo number is invalid dawg" << endl;
              }
         }
	
	
	system("PAUSE");
	return 0;
}

The length of an array must be known at compile-time. In other words, the length must be constant. Therefore, a value only known at run-time cannot be used to determine the array length.

If it’s possible, you can use dynamic memory allocation[1]. This will allow you to create an array during run-time:

1
2
3
4
5
6
7
8
9
10
11
int input(0);

// Get the length of the array:
std::cin >> input;

// Create an array dynamically:
double *dynamic_array(new double[input]);

// Delete the array (MUST DO THIS!):
delete [] dynamic_array;
dynamic_array = 0x0;

References:
[1] http://www.cplusplus.com/doc/tutorial/dynamic/

Wazzak

You could just remove that line, since «addnumber» is not used anywhere else in the program.

However, the explanation is that «c» is an integer with a value not known at compile time (since it is input by the user).

Hence this double addnumber[c] is attempting to define an array with a variable length. This is not usually valid in C++ (though some compilers may accept it).

If you did need to use addnumber[], the simplest solution would be to set it to a size at least as large as required, such as double addnumber[10], and make sure the program never tries to use any element beyond addnumber[9].

Note also the initialisation part = {d,e,f,g,h,i,j}; does not make sense in any case.

I should think the simplest way would be not to use array storage at all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int main()
{
    std::cout << "Enter the amount of numbers to sum: " ;

    unsigned numbers ;
    std::cin >> numbers ;

    std::cout << "Enter the numbersn" ;

    double total = 0.0 ;
    for ( unsigned i=0;  i<numbers; ++i )
    {
        double input ;
        std::cin >> input ;
        total += input ;
    }

    std::cout << "The total is " << total ;
    std::cout << "nThe average is " << total / numbers << 'n' ;
}

Topic archived. No new replies allowed.

error: variable-sized object may not be initialized

Have you ever come across this error?? 

«Understand the error thoroughly, so that it is not required to google in the future» — That’s what I say to myself.

#include <stdio.h>
#include <string.h>

int main()
{   
    int n = 15;
    char arr[n] = "Stunning Palace";
    printf("Arr [%s] and sizeof(arr) [%d] strlen(arr) [%d]n", arr, 
            sizeof(arr), strlen(arr));
    
    return 0;
}

Output:

In function 'main':
Line 7: error: variable-sized object may not be initialized

This error says,
1. Initialization has a problem.
2. Variable-length array has a problem.

The reason for the above error is we initialized the variable-length array which is not recommended.

char ARR_SIZE  = 15;
char arr[ARR_SIZE];
char arr[ARR_SIZE] = {};  //error
char arr[ARR_SIZE] = {0}; //error

An array size can’t be assigned by another initializer (n = 15), but if the size is assigned by an initializer, it becomes a variable-length array. These variable-length arrays are prohibited from being initialized.

#include <stdio.h>
#include <string.h>

int main()
{   
    char ARR_SIZE  = 15;
    char arr[ARR_SIZE] = {};
    
    printf("Arr [%s] and sizeof(arr) [%d] strlen(arr) [%d]n", arr, 
            sizeof(arr), strlen(arr));
    
    return 0;
}

Output:

In function 'main':
Line 7: error: variable-sized object may not be initialized
#include <stdio.h>
#include <string.h>

int main()
{   
    char ARR_SIZE  = 15;
    char arr[ARR_SIZE] = {0};
    
    printf("Arr [%s] and sizeof(arr) [%d] strlen(arr) [%d]n", arr, 
            sizeof(arr), strlen(arr));
    
    return 0;
}

Output:

In function 'main':
Line 7: error: variable-sized object may not be initialized
Line 7: warning: excess elements in array initializer
Line 7: warning: (near initialization for 'arr')

The type of entity to be initialized shall be an array of unknown size or an object type that is not a variable-length array type, so the problem is with initialization. 

This issue can be solved by two-ways.

1. The type of entity to be initialized shall be an object type that is not a variable-length array type.

#include <stdio.h>

int main()
{   
    int n = 15;
    char arr[n];

    sprintf(arr, "Stunning Palace");
    printf("Arr [%s] and sizeof(arr) [%d] strlen(arr) [%d]n", arr, 
            sizeof(arr), strlen(arr));
    
    return 0;
}

Output:

Arr [Stunning Palace] and sizeof(arr) [15] strlen(arr) [15]

Another way of assigning array size is,

#include <stdio.h>
#define ARR_SIZE 15

int main()
{   
    char arr[ARR_SIZE] = "Stunning Palace";
    printf("Arr [%s] and sizeof(arr) [%d] strlen(arr) [%d]n", arr, 
            sizeof(arr), strlen(arr));
    
    return 0;
}

Output:

Arr [Stunning Palace] and sizeof(arr) [15] strlen(arr) [15]

2. The type of entity to be initialized shall be an array of unknown size.

#include <stdio.h>
#include <string.h>

int main()
{
   char arr[] = "Stunning Palace";

    printf("Arr %s and sizeof(arr) %d strlen(arr) %dn", arr, sizeof(arr), strlen(arr));
    
    return 0;
}

Output:

Arr Stunning Palace and sizeof(arr) 16 strlen(arr) 15

Hence, the problem is with initialization with variable-length and not a declaration.

This problem is applicable to integer arrays as well.

#include <stdio.h>

int main()
{
    int n = 6;
    int arr[n] = {1, 2, 3, 4, 5, 6};

    printf("Array before memset() arr %d and sizeof(arr) %d n", arr[5], sizeof(arr));
    
    return 0;
}

Output:

In function 'main':
Line 6: error: variable-sized object may not be initialized
Line 6: warning: excess elements in array initializer
Line 6: warning: (near initialization for 'arr')
Line 6: warning: excess elements in array initializer
Line 6: warning: (near initialization for 'arr')
Line 6: warning: excess elements in array initializer
Line 6: warning: (near initialization for 'arr')
Line 6: warning: excess elements in array initializer
Line 6: warning: (near initialization for 'arr')
Line 6: warning: excess elements in array initializer
Line 6: warning: (near initialization for 'arr')
Line 6: warning: excess elements in array initializer
Line 6: warning: (near initialization for 'arr')

Integer array initialization also can be solved by the above two methods.

  • Ошибка utorrent система не может найти указанный путь writetodisk
  • Ошибка variable must be of type object
  • Ошибка utorrent нет входящих соединений
  • Ошибка variable identifier expected
  • Ошибка utorrent невозможно соединиться