Ошибка 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

As a developer, you may have come across the error message «variable sized object may not be initialized» in your code. This error message may appear when you try to initialize an array with a variable size, but the C compiler cannot determine the size of the array at compile time. In this guide, we will explore the causes of this error and provide troubleshooting tips and solutions to help you fix it.

Causes of the Error

The «variable sized object may not be initialized» error occurs when you try to initialize an array with a variable size, but the size of the array cannot be determined by the C compiler at compile time. This error typically occurs when you use a variable to declare the size of an array, like this:

int size = 10;
int arr[size] = {0};

In this example, the variable size is used to declare the size of the array arr, but the C compiler cannot determine the value of size at compile time, leading to the error message.

Troubleshooting Tips

Here are some troubleshooting tips to help you fix the «variable sized object may not be initialized» error:

  1. Use a constant value to declare the size of the array, like this:
#define SIZE 10
int arr[SIZE] = {0};
  1. Use dynamic memory allocation to allocate memory for the array at runtime, like this:
int size = 10;
int *arr = malloc(size * sizeof(int));
  1. Use a fixed-size array instead of a variable-size array, if possible.

Solutions

Here are some solutions to fix the «variable sized object may not be initialized» error:

  1. Use a constant value to declare the size of the array, like this:
#define SIZE 10
int arr[SIZE] = {0};
  1. Use dynamic memory allocation to allocate memory for the array at runtime, like this:
int size = 10;
int *arr = malloc(size * sizeof(int));
  1. Use a fixed-size array instead of a variable-size array, if possible.

FAQ

What is the «variable sized object may not be initialized» error?

The «variable sized object may not be initialized» error occurs when you try to initialize an array with a variable size, but the C compiler cannot determine the size of the array at compile time.

What causes the «variable sized object may not be initialized» error?

The error occurs when you use a variable to declare the size of an array, and the C compiler cannot determine the value of the variable at compile time.

How can I fix the «variable sized object may not be initialized» error?

You can fix the error by using a constant value to declare the size of the array, using dynamic memory allocation to allocate memory for the array at runtime, or using a fixed-size array instead of a variable-size array.

Can I use a variable to declare the size of an array in C?

Yes, you can use a variable to declare the size of an array in C, but you may encounter the «variable sized object may not be initialized» error if the C compiler cannot determine the size of the array at compile time.

How do I allocate memory for an array in C?

You can allocate memory for an array in C using dynamic memory allocation, like this:

int size = 10;
int *arr = malloc(size * sizeof(int));
  • C Arrays
  • Dynamic Memory Allocation in C

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.

Today we will discuss the ERROR: variable-sized objects may not be initialized in C++. This error message typically appears in C++ when you are trying to initialize a variable-sized object, such as an array, with a non-constant expression. In C++, the size of an array must be a constant expression, so you cannot use a variable or a function call to determine the size of an array. Instead, you should use a constant or a constant expression to specify the size of the array.k.

Table of Contents: 

  1. What is meant by “Error: a variable-sized object may not be initialized in C++”?
  2. Why does this error occur?
  3. How to avoid the error?
    1. Using Constant Expression
    2. By Dynamic Allocation of Memory
    3. Through Vectors
  4. The Conclusion
  5. References

In C++, arrays are a fundamental data structure that are used to store a collection of elements of the same type. However, when declaring an array, the size of the array must be determined by a variable or a function call, as long as the variable or function call is a constant expression. A constant expression is an expression that can be evaluated at compile-time. If you try to initialize an array with a non-constant expression, you will receive the error message “variable sized object may not be initialized.”

For example, some compilers will produce errors on the below code.


#include 
int main()
{
        int n = 5;
        int arr[n];
        return 0;
}

Why does this error occur? 

The error “variable-sized object may not be initialized” occurs in C++ when you try to initialize an object, such as an array, with a non-constant expression. In C++, the size of an array must be a constant expression, which means that the size of the array must be known at compile-time.

For example, in the following code, the variable ‘size’ is not a constant expression, its value is not known at compile-time and it’s determined by the user input. Therefore, the compiler will raise the error “variable-sized object may not be initialized”.


#include 
int main()
{
        int size;
        std::cin >> size;
        int arr[size]; // This will give the error
        return 0;
}

The reason for this is that arrays are stored in memory in a contiguous block and the memory has to be reserved before the program is executed. To reserve the memory, the size of the array must be known at compile-time. If the size of the array is determined at runtime, it’s not possible for the compiler to reserve the memory required for the array.

Additionally, variable-length arrays (VLA) are not part of the C++ standard, and their use is not portable across different compilers and platforms. Some compilers may support VLAs as an extension to the C++ language, but their use is not recommended and may lead to unexpected behavior.

It’s important to note that, using Variable Length Array (VLA) is a C99 feature and not a part of the C++ standard. Some compilers may support VLAs as an extension to the C++ language, but their use is not portable and may lead to unexpected behavior.

How to avoid the error? 

To avoid this error, you can use a constant expression to specify the size of the array. However, If you want to use a variable to specify the size of an array, you can use dynamic memory allocation to allocate memory to variable-sized objects like a vector or a pointer. There are several ways to avoid the error which are explained in the next topics.

Using Constant Expression

We can use a constant expression to specify the size of the array. This way the size of the array is known at compile-time and the memory can be reserved before the program is executed. This can be done as follows:


#include 
int main()
{
        const int size = 5;
        int arr[size];
        return 0;
}

By Dynamic Allocation of Memory

Another method is to use dynamic memory allocation to allocate memory for a variable-sized object. Dynamic memory allocation allows for allocating memory at runtime, which makes it possible to use a variable to specify the size of the array. For example;


#include 
int main()
{
        int size;
        std::cin >> size;
        int* arr = new int[size];
        return 0;
}

Through Vectors

Lastly, there is also the method of using standard C++ containers like std::vectorstd::vector is a standard C++ container that provides dynamic size arrays, it automatically handles memory allocation and deallocation, so you don’t have to worry about it. It can be performed as follows:


#include 
int main()
{
        int size;
        std::cin >> size;
        std::vector<<span class="hljs-type">int> arr(size);
        return 0;
}

The Conclusion

In conclusion, the error “variable-sized object may not be initialized” occurs in C++ when trying to initialize an object, such as an array, with a non-constant expression. In C++, the size of an array must be a constant expression, which means that the size of the array must be known at compile-time. To avoid this error, you can use a constant expression, a constant variable, dynamic memory allocation, or standard C++ containers like std::vector to specify the size of the array. Using the Variable Length Array (VLA) feature is not a part of the C++ standard and its use is not recommended as it’s not portable across different compilers and platforms, it may lead to unexpected behavior.

References

  • Use of Constant Expressions from cppreference
    https://en.cppreference.com/w/cpp/language/constant_expression
  • Dynamic Memory Allocation; Using “new” keyword from cppreference
    https://en.cppreference.com/w/cpp/language/new
  • reference to Vectors from programiz
    https://www.programiz.com/cpp-programming/vectors
  • 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.

Понравилась статья? Поделить с друзьями:
  • Ошибка variable not found in subplan target lists
  • Ошибка uplay has detected an error
  • Ошибка update x64 metadata dat failed crc check
  • Ошибка variable not defined vba
  • Ошибка variable must be of type object 25408