0

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?

Community
  • 1
  • 1
wrongusername
  • 18,564
  • 40
  • 130
  • 214

4 Answers4

2

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.

Nathan Osman
  • 71,149
  • 71
  • 256
  • 361
  • Thanks! I can't make it constant since I have no idea what the size of the string will be. What do you mean by "creating it on the heap?" Sorry, I'm still a novice at programming. – wrongusername Mar 19 '10 at 21:46
  • Allocate memory using `new` and free with `delete` – Nathan Osman Mar 19 '10 at 21:49
  • 1
    Which really means use `vector`. There is *no* reason to have raw memory allocations hanging about, they leak and make your life more difficult. – GManNickG Mar 19 '10 at 22:03
  • I'm not saying use `new` and `delete` directly - I'm just explaining what the heap is. – Nathan Osman Mar 19 '10 at 22:08
1

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

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

John Knoeller
  • 33,512
  • 4
  • 61
  • 92
0

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]

Eugen Constantin Dinca
  • 8,994
  • 2
  • 34
  • 51