开发者

Creating array with constant

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 with开发者_StackOverflow社区out using vectors, since that would require a re-write of many parts of the program?


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.


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


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]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜