• Advertisement
Sign in to follow this  

arrays

This topic is 3495 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a Question about an array.I have code that looks like this. int ArSize = 12; const const char * months[ArSize] = { "January","February","March", "April","May","June", "July","August","September", "October","November","December" }; and it won't compile but when I do this It will work int ArSize = 12; const char * months[12] = { "January","February","March", "April","May","June", "July","August","September", "October","November","December" }; I was wondering why one works and not the other

Share this post


Link to post
Share on other sites
Advertisement
In C++, the size of an array must be a compile-time constant. Since ArSize is not a constant at all in the first example, it cannot be used as an array size.

Note that you can use:

template <typename T, size_t N> size_t array_size(const T (&arr)[N]) 
{ return N; }

const char *months[] = { /* ... */ }
size_t arSize = array_size(months);

Share this post


Link to post
Share on other sites
Your first example won't compile because your compiler won't know what to do about that double const, but here's what I get when I type in your code withonly one: ISO C++ forbids variable-size array.

What this means is, C++ can't handle arrays of variable size; it must know what the size of an array is at compile time. It needs to know how much space to use, even if it's on the stack.

BTW: If by the double const, you meant cont array of const chars, don't worry about it, they are because you defined them with literals. Besides, the syntax for that would be const char* const.

Share this post


Link to post
Share on other sites
Thanks for the replies, and I just accidentlly put another const in their but I know what you were talking about Splinter of Chaos.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement