Gladstone Asder
Gladstone Asder

Reputation: 403

cannot allocate an array of constant size 0

 int len = GetWindowTextLengthW(hwndEdit) + 1;
 wchar_t text[len];

I get

Error 2 error C2466: cannot allocate an array of constant size 0
Error 3 error C2133: 'text' : unknown size
Error 1 error C2057: expected constant expression

I don't understand why it wont compile, because GetWindowTextLengthW(hwndEdit) + 1 > 0

Isn't it true that null+1 = 1?

Upvotes: 1

Views: 9601

Answers (4)

Andy Prowl
Andy Prowl

Reputation: 126432

First of all, you are using the syntax for declaring a statically sized array but you pass in a size variable which is evaluated at run-time. This is why it does not compile.

Second, you cannot allocate an array statically with a size of 0, but that's another issue (although std::array allows you doing that).

I think you should use dynamic allocation instead:

wchar_t* text = new wchar_t[len]

or even better, use std::wstring or std::vector<wchar_t >

Upvotes: 3

Marc Glisse
Marc Glisse

Reputation: 7925

It is true that an error message that complains about a zero instead of a non-constant value is confusing (just like some compilers complain about int for undefined types). VLA are a C99 feature, only present as an extension in some C++ compilers (and on its way to be partially added to C++14 under a different name). The closest equivalent (allocate on the stack, no call to a deallocation function) under MSVC is _alloca.

Upvotes: 0

gustaf r
gustaf r

Reputation: 1234

What you want is not to have to care about memory management, right? That's why you chose a statically allocated array.

Yes, you can use new as the answers here recommend, I however recommend:

std::vector< wchar_t > text;

Upvotes: 4

Andrew
Andrew

Reputation: 12009

Try:

wchar_t* text = new wchar_t[len];

Upvotes: 0

Related Questions