Си error 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}};

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.1k7 gold badges40 silver badges81 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,1421 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

313 bronze badges

1

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.1k7 gold badges40 silver badges81 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,1421 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

313 bronze badges

1

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.1k7 gold badges40 silver badges81 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,1421 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

313 bronze badges

1

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

Содержание

  1. C & C++, Linux & Networking World
  2. Search This Blog
  3. error: variable-sized object may not be initialized
  4. [SYCL] error: variable-sized object may not be initialized #887
  5. Comments
  6. C compile error Variable-sized object may not be initialized with char * pt
  7. All 2 Replies
  8. Ошибка компиляции C: «Объект переменного размера не может быть инициализирован»
  9. 10 ответы

C & C++, Linux & Networking World

Search This Blog

error: variable-sized object may not be initialized

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

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.

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.

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.

Another way of assigning array size is,

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

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

This problem is applicable to integer arrays as well.

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

Источник

[SYCL] error: variable-sized object may not be initialized #887

Is it supposed to be ok? If yes, how can i use a dynamic multidimensional array with USM?

The text was updated successfully, but these errors were encountered:

Hi,
it seems that it’s impossible to capture variable length array by value.
The new_image variable cannot be captured in a standard C++ lambda like:

Compiler gives the same error message on such code.

I believe you need to initialize new_image using malloc_shared to use it in the kernel(preudo-code):

However the crash after diagnostics is a bug.

@romanovvlad thanks. I’ve changed the code following your tip but i have a similar issue.

Hi,
old_image should be allocated in the same way. Attaching diff.
usm_allocation.diff.txt

@romanovvlad i’ve tested in small arrays and it works, but with huge arrays (20000*40000 bytes) it gives me a segmentation fault. Looking with gdb this is the backtrace:

Hm sounds like an issue in compute runtime, suggest creating issue there https://github.com/intel/compute-runtime/issues

I have the feeling that you should use just a 2-D array instead of an array of array, since all the dimensions seem to be constexpr if you do not need this complex data structure.
Even on a CPU this double indirection is inefficient anyway.
But in this example, you could just use 2-D cl::sycl::buffer + accessors instead of USM and explicit memory management.
It gives you this 2-D array-like interface through the accessor for free!

Hi @keryell , i’ve already tried the implementation with the cl::sycl::buffer (you can find here https://github.com/cagnulein/sycl-benchmarks/blob/master/rotate/rotate.cpp) and it works; it has only big issue: is really slow copying 800MB of data from the CPU to GPU and back.

With the USM, if i didn’t misundarstood them, i will run my alghoritm without copying around my buffer. And when it works, it works very quickly! I talk about 8x times faster than cl::sycl:buffer mode.

What do you think?

I see. It depends probably on the the GPU architecture. If you have some efficient shared hardware access between CPU and GPU that makes sense. Otherwise, a 2-D buffer with the right access mode in the accessors (such as write_only. ) might be more efficient, with a minimal number of huge copy instead a gazillions of inefficient individual accesses,

But my 2-D array suggestion was at the first place that it seems super inefficient to have arrays of arrays like

instead of just a plain old C 2-D array:

See https://godbolt.org/z/XkAWqe to get a simpler idea about why it should work (I have not tried myself with oneAPI. )

I hope in the future USM will be extended to allow «just»:

that would provide also some nice alignment properties as a side effect.

A limitation of the current compiler that might not handle references?
Can you try removing the reference by using instead for example

and replacing the old_image by (*old_image) where it is used?

@keryell i’ve tried but this is the result:

Is it supposed to be ok? If yes, how can i use a dynamic multidimensional array with USM?

Источник

C compile error Variable-sized object may not be initialized with char * pt

Yes I did read these two posts.

My case is a bit different because I’m using char * ptr[buflen] . This is what I have tried:

    3 Contributors 2 Replies 8K Views 1 Day Discussion Span Latest Post 7 Years Ago Latest Post by deceptikon

This has to do with what is known at compile time in C. Unless you are using C99 or C++, char *ptr[bufflen] won’t compile. In C89/90, the array size must be a compile time constant, meaning that it is either a number or a macro like so:

This has to do with what is known at compile time in C. Unless you are using C99 or C++, char *ptr[bufflen] won’t compile. In C89/90, the array size must be a compile time constant, meaning that it is either a number or a macro like so:

If you are writing C89/90, your code is compiling due to a compiler extension. I’m not sure of the rationale behind not allowing VLA (variable length array) initializers, but, since it is only allowed as a compiler extension in C89, all you need to know is the compiler doesn’t like it. As for char *strings_line_tokens[503] = <0>; , this is standard C code (as far as I know). As a side note, if you write this at global scope, it gets 0 initialized for you, so you dont need the = <0>part.

The work aroung for this is malloc/calloc. Before I go further, I want to make sure you know what you are allocating. char *ptr[20]; is an array of 20 pointers to char. Thus, its size is sizeof(char*)*20 not buflen*buflen*sizeof(char) . Since you seem to want to initialize your array with zeros, you should consider using calloc instead of malloc, as it will do it for you:

Calloc takes the number of things you want to allocate as its first parameter and the size of each individual thing as its second one.
For learning purposes, here is what it would look like if you were to initialize it manually:

If you are intentionally using VLAs (either through an extension or with C99/C++), you could use memset on it the same way:

The only difference is that you are using an array on the stack, so you don’t have to free it. You do, however, have to free the pointers you get from malloc and calloc, as they are on the heap. Keep in mind, though, that if you store any pointers in your array that point to memory on the heap, you will need to keep track of those pointers ouside of the function or free them before the function returns. Otherwise, you will leak memory.

The last thing I want to mention is that in char *ptrs[20]; «ptrs» is an array while in char* ptrs = (char*)calloc(20, sizeof(char*)); «ptrs» is a pointer that points TO an array on the heap. Thus, sizeof(ptrs) will evaluate to 20*sizeof(char*) in the array version and sizeof(char*) in the calloc version.

I hope this helped!

I’m not sure of the rationale behind not allowing VLA (variable length array) initializers

It’s a combination of not complicating the compiler and not hiding an extremely volatile runtime task behind benign syntax. Even in C99+, VLAs are risky and not something I’d recommend using. Robust code shouldn’t use them, as failure to allocate cannot be recovered from. A solid solution would still use the gamut of VLA, static array, and dynamic array, so cutting out the VLA part would actually simplify code.

you should consider using calloc instead of malloc

I’m torn between saying «no» and «hell no». The problem here is that an array of pointers is being allocated, and calloc encourages a false sense of security that those pointers are initialized to NULL . NULL need not be synonymous with all bits zero, which is what calloc does.

Otherwise, kudos for a good post. You get my upvote. 🙂

Источник

Ошибка компиляции C: «Объект переменного размера не может быть инициализирован»

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

задан 21 июн ’10, 04:06

Как указано в отличном ответе Дэвида Родригеса: если длина является переменной, вам нужен memset, но если длина является константой времени компиляции, тогда оператор компилируется нормально. — Casey

ffwd к 2020 году — enum ; int boardAux[length][length] = <0>; — Chef Gladiator

сделать это const int решил эту проблему для меня. — Mote Zart

10 ответы

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

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

Я могу использовать для этой цели и malloc, насчет второго вопроса, я написал его после ответа Павла — Привет мир

@helloWorld: с выделенными стеком массивами, printf( «%d», boardAux[1][2] ) компилируется нормально. Компилятор знает размеры и знает, в какой позиции в памяти находится (1,2) -й элемент. Если вы используете динамическое размещение, массив является одномерным, и вы должны выполнить математику самостоятельно: printf(«%d», boardAux[ 1*length + 2 ]) — Давид Родригес — дрибеас

@AndreyT: Спасибо, что указали на ошибку в memset вызывать. Я только что поправил. — Давид Родригес — дрибеас

Почему я получаю эту ошибку в компиляторе C99, когда устанавливаю length быть static ? В C ++ 14 все работает нормально. — Силидрон

Я хочу знать причину почему malloc не требуется. — лабиринт

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

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

где ты это нашел, можешь дать ссылку? — Привет мир

@helloWorld: это из языкового стандарта (C99). Вы можете получить «рабочую» копию с обновлениями TC3 здесь open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf — Муравей

Есть темы, по которым некоторые всегда не поверят вам, если вы предоставите только неформальное объяснение. Массивы переменной длины — одна из таких тем. +1 за цитирование стандарта. — Паскаль Куок

@AnT Я запускаю код на C ++, он отлично компилируется, поэтому инициализация массива переменного размера допустима в C ++? — Абхишек Мане

@Abhishek Mane: Нет. В C ++ вообще нет массивов переменного размера. — Муравей

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

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

Но это нормально работает:

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

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

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

ответ дан 27 мар ’16, в 13:03

memset проще и быстрее. — ALX

На этот вопрос уже дан ответ, но я хотел бы указать на другое решение, которое работает быстро и работает, если длина не должна изменяться во время выполнения. Используйте макрос #define перед main (), чтобы определить длину, и в main () ваша инициализация будет работать:

Макросы запускаются до фактической компиляции, и длина будет постоянной времени компиляции (как указано в ответе Дэвида Родригеса). Фактически перед компиляцией длина будет заменена на 10.

ответ дан 12 апр.

есть ли реальная разница между <0>и <<0>> ? — ITJ

Массив не инициализируется указанной памятью, и выдает ошибку. variable sized array may not be initialised Я предпочитаю обычный способ инициализации,

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

ответ дан 02 мар ’16, в 20:03

Я думаю, вам нужно узнать, что означает const! — Хольгер

@Holger: Ты уверен? Если переменная, содержащая длину (не сам массив, а длина массива), является константой, то компилятор знает длину, используемую для инициализации массива. Например, «int length = 5; int array [length];» выдает ошибку, но «Const int length = 5; int array [length]; «компилируется отлично. — Кейси

@Casey: но const int lenght=5; int array[length][length] = <<0>>; не буду. — местрелев

Источник

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.

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

Понравилась статья? Поделить с друзьями:
  • Сзвтд ошибка 50 как исправить
  • Силиконовый чехол болтается как исправить
  • Сзвм ошибка 50 что это
  • Силикон стал липким как исправить
  • Сзв тд сдан частично ошибка 30