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
33.5k49 gold badges174 silver badges310 bronze badges
asked Jan 18, 2011 at 17:37
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 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é NyffeneggerRené Nyffenegger
38.9k32 gold badges157 silver badges284 bronze badges
-
You cannot return a local array. Everything you return will need to be free’d by someone.
-
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 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
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 SmithMichael Smith
4031 gold badge3 silver badges8 bronze badges
2
|
|
|
Определение параметров массивов в языке С
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
1. В книге Харбисона и Стила «Язык С с примерами» (2011 года, стр. 162) указывается, что запись функции вида:
void getArray(int nstr, int ncol) { int a[nstr][ncol]; } Ошибки
error C2057: требуется константное выражение error C2466: невозможно выделить память для массива постоянного нулевого размера error C2057: требуется константное выражение error C2466: невозможно выделить память для массива постоянного нулевого размера error C2087: a: отсутствует индекс Может быть я неправильно понял изложенное в этих книгах? Прикрепляю проект, который компилировал и как С++, и как С. Посмотрите, пожалуйста, может быть я что-то делаю неправильно. Сообщение отредактировано: tumanovalex — 24.12.11, 13:35 |
Adil |
|
Цитата tumanovalex @ 24.12.11, 13:33 2. В книге по C, по-моему, Шилда указано, что в функциях можно использовать локальные массивы конструкции: Или ты не так понял, или выкинь книгу. При объявлении массива nrow и ncol должны быть константами. |
Qraizer |
|
Moderator Рейтинг (т): 520 |
В Стандарте C99 разрешаются локальные в функциях массивы с неконстанстными размерами. В Стандарте C++ такого нет за ненадобностью. Но по-любому массивы в параметрах функций сводятся к указателям. Оно является коррекным в любой ревизии C/C++, но будет игнорироваться. |
D_KEYOnline |
|
Цитата Adil @ 24.12.11, 14:05 Цитата tumanovalex @ 24.12.11, 13:33 2. В книге по C, по-моему, Шилда указано, что в функциях можно использовать локальные массивы конструкции: Или ты не так понял, или выкинь книгу. При объявлении массива nrow и ncol должны быть константами.
В С++. В С — можно и не константами(в C99). |
amk |
|
Цитата D_KEY @ 24.12.11, 17:20 Кстати, новый же стандарт C++ хотели привести в соответствие с C99 C99 так и не стал основным стандартом C. Все еще существуют компиляторы не поддерживаюшие этот стандарт, и это считается нормальным. Учитывая, что в C++ и массивы C89 с константным размером считаются плохим тоном, то становится понятным, почему в стандарт C++ не стали вводить массивы с неизвестным на момент компиляции размером. Тем более, что у C99 и C++ и так хватает несоответствий. Вдобавок подобная таким массивам конструкция, реализованная средствами C++, практически не отличается результатом компиляции. |
MyNameIsIgor |
|
Цитата amk @ 25.12.11, 17:49 C99 так и не стал основным стандартом C А уже вышел C11… |
D_KEYOnline |
|
Цитата amk @ 25.12.11, 17:49 Вдобавок подобная таким массивам конструкция, реализованная средствами C++, практически не отличается результатом компиляции. Это какая же? Разве что извращаться через placement new. |
Qraizer |
|
Moderator Рейтинг (т): 520 |
Зачем? std::vector<> на что? |
D_KEYOnline |
|
Цитата Qraizer @ 26.12.11, 08:12 Зачем? std::vector<> на что? std::vector<> работает с динамической памятью. Можно, конечно, заставить его работать со стэком, но это уже извращение. ИМХО. Сообщение отредактировано: D_KEY — 26.12.11, 08:38 |
Qraizer |
|
Moderator Рейтинг (т): 520 |
Ну и что? Контракты те же. |
D_KEYOnline |
|
Цитата Qraizer @ 26.12.11, 08:41 Ну и что? Контракты те же.
«Контракты» даже лучше у вектора Тут же работа со стэком и ключевая особенность variable-length массивов именно в этом. |
Сыроежка |
|
Цитата tumanovalex @ 24.12.11, 13:33 1. В книге Харбисона и Стила «Язык С с примерами» (2011 года, стр. 162) указывается, что запись функции вида:
void getArray(int nstr, int ncol) { int a[nstr][ncol]; }
Ошибки
1. В книге Харбисона и Стила «Язык С с примерами» (2011 года, стр. 162) указывается, что запись функции вида:
void getArray(int nstr, int ncol) { int a[nstr][ncol]; }
Ошибки Первый ваш вопрос. Для вызова функции getArray нужно в первых двух параметрах указать размеррности массива, передаваемого в качестве третьего аргумента. Например,
int main( void ) { int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; getArray( 2, 3, a ); } Второй ваш вопрос. ваш компилятор выдает сообщения об ошибке, так как он, скорей всего, просто не поддерживает стандарт языка С99. |
Qraizer |
|
Moderator Рейтинг (т): 520 |
Цитата D_KEY @ 26.12.11, 08:50 Тут же работа со стэком и ключевая особенность variable-length массивов именно в этом. Да ну? А я всегда считал, что это не цель, а средство её достижения. А целью является «локальность» выделяемой памяти. Когда-то этим занималась _alloca(), и такие массивы являются результатом её стандартизации. |
D_KEYOnline |
|
Цитата Qraizer @ 27.12.11, 08:39 Цитата D_KEY @ 26.12.11, 08:50 Тут же работа со стэком и ключевая особенность variable-length массивов именно в этом. Да ну? А я всегда считал, что это не цель, а средство её достижения. А целью является «локальность» выделяемой памяти. Я одного не понял, с чем ты спорил? Стэк == локальная память. Сообщение отредактировано: D_KEY — 27.12.11, 08:55 |
Qraizer |
|
Moderator Рейтинг (т): 520 |
С тем, что std::vector<> якобы не является заменой. Является. Поэтому эта C99-фича в Плюсах не нужна. |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ 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: требуется константное выражение
__________________
0 |
Genn55 413 / 250 / 118 Регистрация: 26.12.2012 Сообщений: 786 |
||||||||||||
15.12.2013, 00:20 |
2 |
|||||||||||
Размер массива нужно указывать в объявлении это величина константная и изменить ее после объявления нельзя.
а чтобы иметь произвольный размер нужно выделить память.
и работать как с обычным массивом.В конце программы память нужно освобождать
0 |
StackOverflow All rights reserved. 93 / 83 / 24 Регистрация: 03.08.2013 Сообщений: 258 |
||||
15.12.2013, 09:23 |
3 |
|||
В конце программы память нужно освобождать
Скорее следует освобождать, чего требует хороший стиль программирования. При завершении работы программа всё равно вернёт всю взятую у ОС память обратно.
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 |
|
||||||
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:
|
|
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:
|
|
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.
|
|
R0mai wrote: |
---|
Are you sure you don’t have those line outside a function? |
R0mai’s guess was correct, I see
Do it either like this:
|
|
or like this:
|
|
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 sizeI 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
-
Edited by
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
-
Marked as answer by
-
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
-
Edited by
- 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 sizeI 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
-
Edited by
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
-
Marked as answer by
-
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
-
Edited by