Error c2466 невозможно выделить память для массива постоянного нулевого размера

Why we can do something like for(int i = 0; i imageSize; i=i+3) { buffer[2] = destination->imageData[i]; buffer[1] = destination->

Why we can do something like

        for(int i = 0; i < destination->imageSize; i=i+3)
        { 

            buffer[2] = destination->imageData[i];
            buffer[1] = destination->imageData[i+1];
            buffer[0] = destination->imageData[i+2];
            buffer+=3;
        }

but we can not do

                               char buffer[destination->imageSize];

And how to such thing?

Sorry — I am quite new to C++…

BTW: my point is to create a function that would return a char with an image. If I’d use mem copy how do I delete returned value?

BenMorel's user avatar

BenMorel

33.5k49 gold badges174 silver badges310 bronze badges

asked Jan 18, 2011 at 17:37

Rella's user avatar

2

I have to ask, why do you think they’re at all related? If you couldn’t index an array by runtime variable, it’d be pretty useless for there to even be arrays. Declaring a variable of a size governed by a runtime variable is entirely different and requires fundamental changes to the way the compiler manages automatic memory.

Which is why you can’t do it in C++. This may change, but for now you can’t.

If you really need a variable sized array you need to allocate one dynamically. You can do it the hard, f’d up way (char * buff = new char[size]...delete [] buff;), or you can do it the easy, safer way (std::vector<char> buff(size)). Your choice. You can’t build it «on the stack» though.

answered Jan 18, 2011 at 17:42

Edward Strange's user avatar

Edward StrangeEdward Strange

40.1k7 gold badges71 silver badges124 bronze badges

1

char buffer[destination->imageSize]; declares a variable at compile time. At that time, the value of destination->imageSize is not yet known, which is why it doesn’t work.

The expression buffer[2] = destination->imageData[i]; (or rather the buffer[2] thereof) is evaluated at run time.

answered Jan 18, 2011 at 17:43

René Nyffenegger's user avatar

René NyffeneggerRené Nyffenegger

38.9k32 gold badges157 silver badges284 bronze badges

  1. You cannot return a local array. Everything you return will need to be free’d by someone.

  2. The size of a local array must be constant. Always. This is because there is no special logic around arrays in C++. You can use some object collection of STL.

answered Jan 18, 2011 at 17:42

Al Kepp's user avatar

Al KeppAl Kepp

5,7632 gold badges27 silver badges47 bronze badges

Hmm. Did you try creating a pointer or reference to destination->imageSize and passing that in for the index instead?

answered Jan 18, 2011 at 17:44

Rachel McMahan's user avatar

Using std::vector you can achieve what you desire. Your function can be defined something like this:

void readImage(std::vector<char>& imageData, std::string& filename)
{
    size_t imageSize = 0;
    //read file and load imageSize
    imageData.resize(imageSize);
    // load image into imageData using such as you in your question
    for(int i = 0; i < destination->imageSize; i=i+3)
    { 

        buffer[2] = destination->imageData[i];
        buffer[1] = destination->imageData[i+1];
        buffer[0] = destination->imageData[i+2];
        buffer+=3;
    }
}

For further improvements you could return a bool that indicates success or failure.

Regarding the cause of C2466, I don’t have the official answer but you can declare char arrays with const variables only like so:

const int imageSize = 4242; 
char imageData[imageSize]; // No C2466 error

answered Jan 18, 2011 at 17:50

Michael Smith's user avatar

Michael SmithMichael Smith

4031 gold badge3 silver badges8 bronze badges

2

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    Определение параметров массивов в языке С

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему

      


    Сообщ.
    #1

    ,
    24.12.11, 13:33

      1. В книге Харбисона и Стила «Язык С с примерами» (2011 года, стр. 162) указывается, что запись функции вида:
      void getArray(int nstr, int ncol, int a[nstr][ncol]) {…}
      является корректным. Я не очень понял, как тогда нужно объявлять массив «a» в основной программе для правильного вызова функции.
      2. В книге по C, по-моему, Шилда указано, что в функциях можно использовать локальные массивы конструкции:

      ExpandedWrap disabled

        void getArray(int nstr, int ncol)

        {

        int a[nstr][ncol];

        }

      Ошибки

      ExpandedWrap disabled

        error C2057: требуется константное выражение

        error C2466: невозможно выделить память для массива постоянного нулевого размера

        error C2057: требуется константное выражение

        error C2466: невозможно выделить память для массива постоянного нулевого размера

        error C2087: a: отсутствует индекс

      Может быть я неправильно понял изложенное в этих книгах? Прикрепляю проект, который компилировал и как С++, и как С. Посмотрите, пожалуйста, может быть я что-то делаю неправильно.

      Прикреплённый файлПрикреплённый файлMy_ConsConly.zip (2,21 Кбайт, скачиваний: 94)

      Сообщение отредактировано: tumanovalex — 24.12.11, 13:35


      Adil



      Сообщ.
      #2

      ,
      24.12.11, 14:05

        Цитата tumanovalex @ 24.12.11, 13:33

        2. В книге по C, по-моему, Шилда указано, что в функциях можно использовать локальные массивы конструкции:

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

        Guru

        Qraizer



        Сообщ.
        #3

        ,
        24.12.11, 16:20

          Moderator

          *******

          Рейтинг (т): 520

          В Стандарте C99 разрешаются локальные в функциях массивы с неконстанстными размерами. В Стандарте C++ такого нет за ненадобностью. Но по-любому массивы в параметрах функций сводятся к указателям. Оно является коррекным в любой ревизии C/C++, но будет игнорироваться.


          D_KEY
          Online



          Сообщ.
          #4

          ,
          24.12.11, 17:20

            Цитата Adil @ 24.12.11, 14:05

            Цитата tumanovalex @ 24.12.11, 13:33

            2. В книге по C, по-моему, Шилда указано, что в функциях можно использовать локальные массивы конструкции:

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

            В С++. В С — можно и не константами(в C99).
            Кстати, новый же стандарт C++ хотели привести в соответствие с C99 :-?


            amk



            Сообщ.
            #5

            ,
            25.12.11, 17:49

              Цитата D_KEY @ 24.12.11, 17:20

              Кстати, новый же стандарт C++ хотели привести в соответствие с C99

              C99 так и не стал основным стандартом C. Все еще существуют компиляторы не поддерживаюшие этот стандарт, и это считается нормальным.

              Учитывая, что в C++ и массивы C89 с константным размером считаются плохим тоном, то становится понятным, почему в стандарт C++ не стали вводить массивы с неизвестным на момент компиляции размером. Тем более, что у C99 и C++ и так хватает несоответствий. Вдобавок подобная таким массивам конструкция, реализованная средствами C++, практически не отличается результатом компиляции.


              MyNameIsIgor



              Сообщ.
              #6

              ,
              25.12.11, 22:27

                Цитата amk @ 25.12.11, 17:49

                C99 так и не стал основным стандартом C

                А уже вышел C11…


                D_KEY
                Online



                Сообщ.
                #7

                ,
                26.12.11, 06:43

                  Цитата amk @ 25.12.11, 17:49

                  Вдобавок подобная таким массивам конструкция, реализованная средствами C++, практически не отличается результатом компиляции.

                  Это какая же? Разве что извращаться через placement new.

                  Guru

                  Qraizer



                  Сообщ.
                  #8

                  ,
                  26.12.11, 08:12

                    Moderator

                    *******

                    Рейтинг (т): 520

                    Зачем? std::vector<> на что?


                    D_KEY
                    Online



                    Сообщ.
                    #9

                    ,
                    26.12.11, 08:37

                      Цитата Qraizer @ 26.12.11, 08:12

                      Зачем? std::vector<> на что?

                      std::vector<> работает с динамической памятью. Можно, конечно, заставить его работать со стэком, но это уже извращение. ИМХО.

                      Сообщение отредактировано: D_KEY — 26.12.11, 08:38

                      Guru

                      Qraizer



                      Сообщ.
                      #10

                      ,
                      26.12.11, 08:41

                        Moderator

                        *******

                        Рейтинг (т): 520

                        Ну и что? Контракты те же.


                        D_KEY
                        Online



                        Сообщ.
                        #11

                        ,
                        26.12.11, 08:50

                          Цитата Qraizer @ 26.12.11, 08:41

                          Ну и что? Контракты те же.

                          «Контракты» даже лучше у вектора :) Тут же работа со стэком и ключевая особенность variable-length массивов именно в этом.
                          Разговор изначально вообще-то о С был.
                          Но я так и не понял, почему в новом стандарте С++ все-таки отказались от обещанной совместимости с C99?


                          Сыроежка



                          Сообщ.
                          #12

                          ,
                          26.12.11, 19:59

                            Цитата tumanovalex @ 24.12.11, 13:33

                            1. В книге Харбисона и Стила «Язык С с примерами» (2011 года, стр. 162) указывается, что запись функции вида:
                            void getArray(int nstr, int ncol, int a[nstr][ncol]) {…}
                            является корректным. Я не очень понял, как тогда нужно объявлять массив «a» в основной программе для правильного вызова функции.
                            2. В книге по C, по-моему, Шилда указано, что в функциях можно использовать локальные массивы конструкции:

                            ExpandedWrap disabled

                              void getArray(int nstr, int ncol)

                              {

                              int a[nstr][ncol];

                              }

                            Ошибки
                            Может быть я неправильно понял изложенное в этих книгах? Прикрепляю проект, который компилировал и как С++, и как С.

                            1. В книге Харбисона и Стила «Язык С с примерами» (2011 года, стр. 162) указывается, что запись функции вида:
                            void getArray(int nstr, int ncol, int a[nstr][ncol]) {…}
                            является корректным. Я не очень понял, как тогда нужно объявлять массив «a» в основной программе для правильного вызова функции.
                            2. В книге по C, по-моему, Шилда указано, что в функциях можно использовать локальные массивы конструкции:

                            ExpandedWrap disabled

                              void getArray(int nstr, int ncol)

                              {

                              int a[nstr][ncol];

                              }

                            Ошибки
                            Может быть я неправильно понял изложенное в этих книгах? Прикрепляю проект, который компилировал и как С++, и как С.

                            Первый ваш вопрос. Для вызова функции getArray нужно в первых двух параметрах указать размеррности массива, передаваемого в качестве третьего аргумента.

                            Например,

                            ExpandedWrap disabled

                              int main( void )

                              {

                                 int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };

                                 getArray( 2, 3, a );

                              }

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

                            Guru

                            Qraizer



                            Сообщ.
                            #13

                            ,
                            27.12.11, 08:39

                              Moderator

                              *******

                              Рейтинг (т): 520

                              Цитата D_KEY @ 26.12.11, 08:50

                              Тут же работа со стэком и ключевая особенность variable-length массивов именно в этом.

                              Да ну? А я всегда считал, что это не цель, а средство её достижения. А целью является «локальность» выделяемой памяти. Когда-то этим занималась _alloca(), и такие массивы являются результатом её стандартизации.


                              D_KEY
                              Online



                              Сообщ.
                              #14

                              ,
                              27.12.11, 08:54

                                Цитата Qraizer @ 27.12.11, 08:39

                                Цитата D_KEY @ 26.12.11, 08:50

                                Тут же работа со стэком и ключевая особенность variable-length массивов именно в этом.

                                Да ну? А я всегда считал, что это не цель, а средство её достижения. А целью является «локальность» выделяемой памяти.

                                Я одного не понял, с чем ты спорил? Стэк == локальная память.

                                Сообщение отредактировано: D_KEY — 27.12.11, 08:55

                                Guru

                                Qraizer



                                Сообщ.
                                #15

                                ,
                                27.12.11, 09:32

                                  Moderator

                                  *******

                                  Рейтинг (т): 520

                                  С тем, что std::vector<> якобы не является заменой. Является. Поэтому эта C99-фича в Плюсах не нужна.

                                  0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                                  0 пользователей:

                                  • Предыдущая тема
                                  • C/C++: Общие вопросы
                                  • Следующая тема

                                  Рейтинг@Mail.ru

                                  [ Script execution time: 0,0428 ]   [ 18 queries used ]   [ Generated: 9.02.23, 12:12 GMT ]  

                                  Passvv0rd

                                  0 / 0 / 0

                                  Регистрация: 14.12.2013

                                  Сообщений: 5

                                  1

                                  Массивы : невозможно выделить память для массива постоянного нулевого размера

                                  14.12.2013, 23:43. Показов 4227. Ответов 2

                                  Метки нет (Все метки)


                                  Помогите или направьте.

                                  1>3.cpp(10): error C2057: требуется константное выражение
                                  1>3.cpp(10): error C2466: невозможно выделить память для массива постоянного нулевого размера
                                  1>3.cpp(10): error C2133: mas: неизвестный размер

                                  C++
                                  1
                                  2
                                  3
                                  4
                                  5
                                  6
                                  7
                                  8
                                  9
                                  10
                                  11
                                  12
                                  13
                                  14
                                  15
                                  16
                                  
                                  //Сформировать массив из n элементов с помощью датчика случайны чисел (n задается пользователем с клавиатуры)
                                  #include "stdafx.h"
                                  #include "stdio.h"
                                  #include "locale"
                                  #include "iostream"
                                  int main()
                                  {
                                      using namespace std;
                                      setlocale(LC_ALL,"Russian");
                                      int i, n, mas[n];
                                        cout<<"Введите кол-во элементов массива";
                                        cin>>n;
                                        for (int i=0; i<n; i++){
                                            mas[i]=rand()%100;}
                                      return 0;
                                  }

                                  __________________
                                  Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



                                  0



                                  Genn55

                                  413 / 250 / 118

                                  Регистрация: 26.12.2012

                                  Сообщений: 786

                                  15.12.2013, 00:20

                                  2

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

                                  C++
                                  1
                                  
                                  const int n = 10;

                                  а чтобы иметь произвольный размер нужно выделить память.

                                  C++
                                  1
                                  2
                                  
                                     int n;
                                      int *a = new int [n]; // одномерный динамический массив

                                  и работать как с обычным массивом.В конце программы память нужно освобождать

                                  C++
                                  1
                                  
                                  delete [] a;



                                  0



                                  StackOverflow

                                  All rights reserved.

                                  93 / 83 / 24

                                  Регистрация: 03.08.2013

                                  Сообщений: 258

                                  15.12.2013, 09:23

                                  3

                                  Цитата
                                  Сообщение от Genn55
                                  Посмотреть сообщение

                                  В конце программы память нужно освобождать

                                  C++
                                  1
                                  
                                  delete [] a;

                                  Скорее следует освобождать, чего требует хороший стиль программирования. При завершении работы программа всё равно вернёт всю взятую у ОС память обратно.



                                  0



                                  Bug #63130 «cannot allocate an array of constant size 0» or «dllimport not allowed»
                                  Submitted: 2012-09-21 11:55 UTC Modified: 2012-10-01 13:25 UTC
                                  Votes: 1
                                  Avg. Score: 5.0 ± 0.0
                                  Reproduced: 0 of 0 (0.0%)
                                  From: gospodin dot p dot zh at gmail dot com Assigned: ab (profile)
                                  Status: Closed Package: Compile Failure
                                  PHP Version: 5.3Git-2012-09-21 (snap) OS: Windows
                                  Private report: No CVE-ID: None

                                   [2012-09-21 11:55 UTC] gospodin dot p dot zh at gmail dot com

                                  Description:
                                  ------------
                                  #include <iostream>
                                  //#include "php_test_empty.h"
                                  #include "targetver.h"
                                  #include "php.h"
                                  
                                  ------------
                                  >c:program files (x86)microsoft visual studio 9.0vcincludesysstat.inl(44) 
                                  : error C2466: невозможно выделить память для массива постоянного нулевого 
                                  размера
                                  1>c:program files (x86)microsoft visual studio 9.0vcincludesysstat.inl(49) 
                                  : error C2466: невозможно выделить память для массива постоянного нулевого 
                                  размера
                                  1>c:program files (x86)microsoft visual studio 
                                  9.0vcincludesysutime.inl(39) : error C2466: невозможно выделить память для 
                                  массива постоянного нулевого размера
                                  1>c:program files (x86)microsoft visual studio 
                                  9.0vcincludesysutime.inl(44) : error C2466: невозможно выделить память для 
                                  массива постоянного нулевого размера
                                  1>c:program files (x86)microsoft visual studio 
                                  9.0vcincludesysutime.inl(49) : error C2466: невозможно выделить память для 
                                  массива постоянного нулевого размера
                                  1>c:program files (x86)microsoft visual studio 
                                  9.0vcincludesysutime.inl(78) : error C2466: невозможно выделить память для 
                                  массива постоянного нулевого размера
                                  
                                  ----------
                                  means "cannot allocate an array of constant size 0"
                                  
                                  DO SOMETHING FINALLY!!!!!!!11111oneone
                                  MS Visual Studio 2005 don't exists any more. Make your sources up to date with 
                                  IDE with less spaghetti-code. 
                                  
                                  Expected result:
                                  ----------------
                                  i've expected to make an extension which can use <string> and <iostream>
                                  
                                  Actual result:
                                  --------------
                                  "cannot allocate an array of constant size 0"
                                  or 
                                  "definition dllimport not allowed"
                                  
                                  

                                  Patches

                                  Add a Patch

                                  Pull Requests

                                  Add a Pull Request

                                  History

                                  AllCommentsChangesGit/SVN commitsRelated reports

                                   [2012-09-21 12:53 UTC] laruence@php.net

                                  here is a tricky way to fix this, please try with it:
                                  
                                  vi {THE VS INSTALL FODLER}vcincludemalloc.h 
                                  
                                  change the line:
                                  #define _STATIC_ASSERT(expr) typedef char __static_assert_t[ (expr) ]  
                                  
                                  to:
                                  
                                  #ifdef PHP_WIN32  
                                  #define _STATIC_ASSERT(expr) typedef char __static_assert_t[ (expr)?(expr):1 ]  
                                  #else  
                                  #define _STATIC_ASSERT(expr) typedef char __static_assert_t[ (expr) ]  
                                  #endif
                                  

                                   [2012-09-21 13:18 UTC] gospodin dot p dot zh at gmail dot com

                                  <i>[2012-09-21 12:53 UTC] laruence@php.net
                                  here is a tricky way to fix this, please try with it: </i>
                                  ----------------------
                                  IMPOSIBRU!!1 This worked fine! Thanks a lot! I've spend 2 days trying to solve one 
                                  of those errors. Finally i can go on writing extension which can give me the only 
                                  instance of COM connection to third part application on apache server, available 
                                  and same for each web-site user (session).
                                  

                                   [2012-10-01 13:25 UTC] ab@php.net

                                  -Status: Open
                                  +Status: Closed
                                  -Assigned To:
                                  +Assigned To: ab

                                   [2012-10-01 13:25 UTC] ab@php.net

                                  this looks like solved :)
                                  
                                  • Forum
                                  • Beginners
                                  • cannot allocate an array of constant siz

                                  cannot allocate an array of constant size 0

                                  Hi there, I’m a bit new to C++, but not programming in general.

                                  I have no idea why this code:

                                  1
                                  2
                                  3
                                  4| float densityList[2];
                                  5| densityList[0]			= 6.0F;
                                  6| densityList[1]			= 13.0F;

                                  Is generating this error:

                                  ...arrays.cpp(5) : error C2466: cannot allocate an array of constant size 0

                                  Line 5 is causing the error, but I’m not trying to create a zero length array, I want to set the value for the first item in the array.

                                  I’m sure I’m missing some basic syntax but from the arrays page here it all seems to be in order.

                                  Last edited on

                                  This works ok for me:

                                  1
                                  2
                                  3
                                  4
                                  5
                                  6
                                  7
                                  8
                                  9
                                  10
                                  11
                                  12
                                  13
                                  14
                                  15
                                  16
                                  17
                                  #include <iostream>
                                  using namespace std;
                                  
                                  int main()
                                  {
                                      float densityList[2];
                                  
                                      densityList[0]=6.0f;
                                      densityList[1]=13.0f;
                                  
                                      cout << densityList[0] << endl;
                                      cout << densityList[1] << endl;
                                  
                                      cout << "nhit enter to quit...";
                                      cin.get();
                                      return 0;
                                  }

                                  Could I see the whole code?

                                  Thats basically it, its just a long list of Arrays (no main function). They all get that error though.

                                  Well the code you posted works, so the problem must be elsewhere. You’ll have to post more code if you’ll want us to spot the problem.

                                  Are you sure you don’t have those line outside a function?

                                  Okay, heres the entire .cpp. I’m working with a non-standard library so things may look odd.

                                  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
                                  #include "SkyGame.h"
                                  
                                  using namespace C4;
                                  
                                  float densityList[2];
                                  densityList[kGas]			= 6.0F;
                                  densityList[kSolid]			= 13.0F;
                                  
                                  unsigned long resFoodMinList[2];
                                  unsigned long resFoodMaxList[2];
                                  resFoodMinList[kGas]		= 0;
                                  resFoodMaxList[kGas]		= 20;
                                  resFoodMinList[kSolid]		= 0;
                                  resFoodMaxList[kSolid]		= 100;
                                  
                                  unsigned long resFuelMinList[2];
                                  unsigned long resFuelMaxList[2];
                                  resFuelMinList[kGas]		= 0;
                                  resFuelMaxList[kGas]		= 75;
                                  resFuelMinList[kSolid]		= 0;
                                  resFuelMaxList[kSolid]		= 100;
                                  
                                  unsigned long resOreMinList[2];
                                  unsigned long resOreMaxList[2];
                                  resOreMinList[kGas]			= 0;
                                  resOreMaxList[kGas]			= 100;
                                  resOreMinList[kSolid]		= 0;
                                  resOreMaxList[kSolid]		= 75;
                                  
                                  unsigned long resDustMinList[2];
                                  unsigned long resDustMaxList[2];
                                  resDustMinList[0]			= 0;
                                  resDustMaxList[0]			= 30;
                                  resDustMinList[kSolid]		= 0;
                                  resDustMaxList[kSolid]		= 15;
                                  
                                  String<20> planetNameList[24];
                                  planetNameList[0]			= "Alpha";
                                  planetNameList[1]			= "Beta";
                                  planetNameList[2]			= "Gamma";
                                  planetNameList[3]			= "Delta";
                                  planetNameList[4]			= "Epsilon";
                                  planetNameList[5]			= "Zeta";
                                  planetNameList[6]			= "Eta";
                                  planetNameList[7]			= "Theta";
                                  planetNameList[8]			= "Lota";
                                  planetNameList[9]			= "Kappa";
                                  planetNameList[10]			= "Lambda";
                                  planetNameList[11]			= "Mu";
                                  planetNameList[12]			= "Nu";
                                  planetNameList[13]			= "Xi";
                                  planetNameList[14]			= "Omicron";
                                  planetNameList[15]			= "Pi";
                                  planetNameList[16]			= "Rho";
                                  planetNameList[17]			= "Sigma";
                                  planetNameList[18]			= "Tau";
                                  planetNameList[19]			= "Upsilon";
                                  planetNameList[20]			= "Phi";
                                  planetNameList[21]			= "Chi";
                                  planetNameList[22]			= "Psi";
                                  planetNameList[23]			= "Omega";
                                  
                                  String<5> planetSuffixList[14];
                                  planetSuffixList[0]			= "I";
                                  planetSuffixList[1]			= "II";
                                  planetSuffixList[2]			= "III";
                                  planetSuffixList[3]			= "IV";
                                  planetSuffixList[4]			= "V";
                                  planetSuffixList[5]			= "VI";
                                  planetSuffixList[6]			= "VII";
                                  planetSuffixList[7]			= "VIII";
                                  planetSuffixList[8]			= "IX";
                                  planetSuffixList[9]			= "X";
                                  planetSuffixList[10]		= "A";
                                  planetSuffixList[11]		= "B";
                                  planetSuffixList[12]		= "C";
                                  planetSuffixList[13]		= "D";

                                  R0mai wrote:
                                  Are you sure you don’t have those line outside a function?

                                  R0mai’s guess was correct, I see :P

                                  Do it either like this:

                                  1
                                  2
                                  3
                                  float densityList[2]= {6.0F,13.0F};
                                  
                                  //... 

                                  or like this:

                                  1
                                  2
                                  3
                                  4
                                  5
                                  6
                                  7
                                  8
                                  9
                                  10
                                  11
                                  12
                                  13
                                  14
                                  15
                                  16
                                  17
                                  18
                                  float densityList[2];
                                  
                                  //...
                                  
                                  void init()
                                  {
                                      densityList[kGas]= 6.0F;
                                      densityList[kSolid]= 13.0F;
                                  
                                      //...
                                  }
                                  
                                  int main()
                                  {
                                      init(); //call init here
                                  
                                      //...
                                  }

                                  okay, will try that after work, thanks.

                                  Topic archived. No new replies allowed.

                                  • Remove From My Forums
                                  • Question

                                  • I’m trying to statically allocate memory for an array using a const int instead of hardcoding the number of elements in the array declaration.

                                    const int ARRAY_SIZE = 20;    
                                    
                                    /* declaration of the array */    
                                    int values[ARRAY_SIZE];

                                    But on compiling I get the following errors:

                                     error C2057: expected constant expression
                                     error C2466: cannot allocate an array of constant size 0
                                     error C2133: ‘values’ : unknown size

                                    I don’t get it because the rest of the code that’s using the variable ARRAY_SIZE.

                                    (which is a couple of function calls) is fine with it and see it correctly as 20.

                                    Plus if I change ARRAY_SIZE to the integer literal 20, the compiler doesn’t complain.

                                    I’d appreciate any comments that could shed some light on the matter. I could have

                                    just left the literal 20 in there but it bothers me that code I’ve written countless of times

                                    before now generates an error.

                                    I’m using VC++ 2010 Express Edition.


                                    • Edited by

                                      Saturday, September 29, 2012 2:12 PM

                                  Answers

                                  • I’m trying to statically allocate memory for an array using a const int instead of hardcoding the number of elements in the array declaration.

                                    That’s allowed in C++ but not in C (as implemented by
                                    VC++ according to the C89/90 ANSI/ISO C Standard). If
                                    your program has the .C extension it will be compiled
                                    using the C compiler by default. If it has *.CPP it
                                    will be compiled using the C++ compiler by default.
                                    These defaults can be overridden via the project
                                    properties.

                                    C99 allows VLAs (Variable Length Arrays) but VC++
                                    hasn’t implemented that feature.

                                    — Wayne

                                    • Marked as answer by
                                      Damon ZhengModerator
                                      Friday, October 5, 2012 6:50 AM

                                  • Not knowing the project type you created, I wrote this simple program that compiles and runs in both VS 2010 Express and VS 2012 Express Desktop.

                                    Perhaps looking at this code will help you see the issues in yours. If not, please post a short complete program that will not compile on your system.

                                    #include <iostream>
                                    
                                    using namespace std;
                                    
                                    const int SIZE = 100;
                                    
                                    int main()
                                    {
                                    	int myArray[SIZE];
                                    	cout << "Array created" << endl;
                                    	cin.get();
                                    	return 0;
                                    }

                                    Also, please tell us which VC++ Express version you are using.

                                    • Edited by
                                      pvdg42
                                      Saturday, September 29, 2012 2:29 PM
                                    • Marked as answer by
                                      Damon ZhengModerator
                                      Friday, October 5, 2012 6:51 AM

                                  • Remove From My Forums
                                  • Question

                                  • I’m trying to statically allocate memory for an array using a const int instead of hardcoding the number of elements in the array declaration.

                                    const int ARRAY_SIZE = 20;    
                                    
                                    /* declaration of the array */    
                                    int values[ARRAY_SIZE];

                                    But on compiling I get the following errors:

                                     error C2057: expected constant expression
                                     error C2466: cannot allocate an array of constant size 0
                                     error C2133: ‘values’ : unknown size

                                    I don’t get it because the rest of the code that’s using the variable ARRAY_SIZE.

                                    (which is a couple of function calls) is fine with it and see it correctly as 20.

                                    Plus if I change ARRAY_SIZE to the integer literal 20, the compiler doesn’t complain.

                                    I’d appreciate any comments that could shed some light on the matter. I could have

                                    just left the literal 20 in there but it bothers me that code I’ve written countless of times

                                    before now generates an error.

                                    I’m using VC++ 2010 Express Edition.


                                    • Edited by

                                      Saturday, September 29, 2012 2:12 PM

                                  Answers

                                  • I’m trying to statically allocate memory for an array using a const int instead of hardcoding the number of elements in the array declaration.

                                    That’s allowed in C++ but not in C (as implemented by
                                    VC++ according to the C89/90 ANSI/ISO C Standard). If
                                    your program has the .C extension it will be compiled
                                    using the C compiler by default. If it has *.CPP it
                                    will be compiled using the C++ compiler by default.
                                    These defaults can be overridden via the project
                                    properties.

                                    C99 allows VLAs (Variable Length Arrays) but VC++
                                    hasn’t implemented that feature.

                                    — Wayne

                                    • Marked as answer by
                                      Damon ZhengModerator
                                      Friday, October 5, 2012 6:50 AM

                                  • Not knowing the project type you created, I wrote this simple program that compiles and runs in both VS 2010 Express and VS 2012 Express Desktop.

                                    Perhaps looking at this code will help you see the issues in yours. If not, please post a short complete program that will not compile on your system.

                                    #include <iostream>
                                    
                                    using namespace std;
                                    
                                    const int SIZE = 100;
                                    
                                    int main()
                                    {
                                    	int myArray[SIZE];
                                    	cout << "Array created" << endl;
                                    	cin.get();
                                    	return 0;
                                    }

                                    Also, please tell us which VC++ Express version you are using.

                                    • Edited by
                                      pvdg42
                                      Saturday, September 29, 2012 2:29 PM
                                    • Marked as answer by
                                      Damon ZhengModerator
                                      Friday, October 5, 2012 6:51 AM

                                  Понравилась статья? Поделить с друзьями:
                                • Error c2440 function style cast
                                • Error c2429 для функция языка структурированные привязки нужен флаг компилятора std c 17
                                • Error c2415 недопустимый тип операнда
                                • Error c2374 i redefinition multiple initialization
                                • Error c2365 c