Variable sized object may not be initialized

почему я получаю сообщение об ошибке "объект переменного размера не может быть инициализирован" со следующим кодом?

8 ответов:

Я предполагаю, что вы используете компилятор C99 (с поддержкой массивов динамического размера). Проблема в вашем коде заключается в том, что в то время, когда компиляторы видят ваше объявление переменной, он не может знать, сколько элементов есть в массиве (я также предполагаю здесь, из ошибки компилятора, что length не является константой времени компиляции).

вы должны вручную инициализировать этот массив:

вы получаете эту ошибку, потому что в языке C вы не можете использовать инициализаторы с массивами переменной длины. Сообщение об ошибке вы получаете в основном говорит все это.

3 тип инициализируемого объекта должен быть массив неизвестного размера или объект тип, который не является переменной длиной тип массива.

это дает ошибку:

Это также дает ошибку:

но это прекрасно работает:

вы должны поставить значение следующим образом:

после объявления массива

самый простой способ присвоить начальные значения нулю — это использовать цикл for, даже если он может быть немного длинным

просто объявить длину, чтобы быть минусы, если это не так, то вы должны выделять память динамически

для C++ отдельное объявление и инициализация, как это..

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

7 Answers 7

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).

Читайте также:  Delphi функция возвращает массив

This error occurs when you are trying to use a local variable without initializing it. You won’t get this error if you use a uninitialized class or instance variable because they are initialized with their default value e.g. Reference types are initialized with null and integer types are initialized with zero, but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.

Let’s see couple of examples:

You can see we are trying to access variable "b" which is not initialized in the statement c = a + b , hence when you run this program in Eclipse, you will get following error:

The error message is very clear, it’s saying that local variable "b" has not initialized until line 14, where it has been read, which violates the Java rule of initializing the local variable before use.

Though, this rule is only for local variable, if you try to access uninitialized member variables e.g. a static or non-static variable, you will not get this error as shown below:

This program will both compile and run fine.

How to fix "variable might not have been initialized" error in Java

Now, there are some tricky scenarios where you think that you have initialized the variable but compiler thinks otherwise and throws "variable might not have been initialized" error. One of them is creating more than one local variable in the same line as shown in following Java program:

Читайте также:  Dawicontrol dc 150 raid controller

Here you might think that both variable "a" and "b" are initialized to zero but that’s not correct. Only variable b is initialized and variable "a" is not initialized, hence when you run this program, you will get the "variable might not have been initialized" error as shown below:

Again, the error message is very precise, it says that variable "a" is not initialized on line 13 where you have used it for reading its value. See Core Java Volume 1 — Fundamentals to learn more about how variables are initialized in Java.

One more scenario, where compiler complains about "variable might not have been initialized" is when you initialize the variable ins >if() block, since if is a condition block, compiler know that variable may not get initialized when if block is not executed, so it complains as shown in the following program:

In this case, the variable count will not be initialized before you use it on System.out.println() statement if args.length is zero, hence compiler will throw "variable might not have been initialized" when you run this program as shown below:

Now, sometimes, you will think that compiler is wrong because you know that variable is always going to be initialized but in reality, compilers are not as smart as you and you see this error as shown in the following program:

Now, you know that count will alway initialize because length of argument array would either be zero or greater than zero, but compiler is not convinced and it will throw the "variable might not have been initialized" error as shown below:

Читайте также:  Ga ma790x ds4 драйвера

One way to convince the compiler is use the else block, this will satisfy the compiler and the error will go away as shown below:

Rate this post

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *