Question

I was working on a program in Netbeans on Linux using a gcc compiler when, upon switching to Visual C++ on Windows 7, the code failed to compile as Visual C++ says it expected constant expression on several lines. On Netbeans, I simply did something similar to char name[fullName.size()];, while on Visual C++, I tried, among other things,

const int position = fullName.size();
char Name[position];

How can I create a constant to use for the array?

Note: I know about this question, but is there any way I can get this working without using vectors, since that would require a re-write of many parts of the program?

Was it helpful?

Solution

In VC++ you can't do runtime declarations of stack array sizes, but you can do stack allocation via _alloca

so this:

const int position = fullName.size();
char Name[position];

becomes this:

const int position = fullName.size();
char * Name = (char*)_alloca(position * sizeof(char));

It's not quite the same thing, but it's as close as you are going to get in VC++.

OTHER TIPS

This is not possible in VC++. I know, pretty sad :(

The solutions include:

  • Create it on the heap
  • Make it constant

The new C++ standard (C++0x) proposes a 'constant expression' feature to deal with this. For more info, check this out.

C++ requires that the size of the array be known at compile time. If you don't mind using a non-standard extension, gcc does allow code like you're doing (note that while it's not standard C++, it is standard in C, as of C99).

I'd also guess that you could use a vector (in this particular place) with less trouble than you believe though -- quite a bit of code that's written for an array can work with a vector with only a re-compile, and little or no rewriting at all.

Your char name[fullName.size()]; is an example of a variable-length array which - as far as I know - are not standardized in C++ so you're at the mercy of the compiler. [Slightly off-topic they're part of the C99 standard]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top