Since when can't you use a variable in a char array in c++?

Started by
9 comments, last by link161 13 years, 3 months ago
I'm using VS2010 and it should be a simple declaration:
len=strlen(mine);
char guessed[len];

it keeps telling me it needs to be a constant value, but I've declared this before.

I even tried char guessed[strlen(len)]
and get the same error, any help?
Advertisement
The size of an array needs to be statically known. There are couple of options for you :

1)Use std::string
2)Use std::vector<char>
3)Use dynamic arrays
4)Create a large char array, ex char array[1000]; and have a variable for its length
5)Implement your own.
Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github
Try this:

len=strlen(mine);
const int x = len;
char guessed[x];

Edit: the options above might work to.
Just for completeness:
6) char* Guessed = new char[len];

But don't forget to delete[] it afterwards!
delete[] Guessed;
The compiler is right about showing an error, this is not legal.

However:
1. it is legal if you do it with a constant string, since the compiler will be able to determine that the length is actually constant (so char* x[strlen("foo")]; is legal)
2. it is legal with gcc, since gcc supports non-constant-length arrays as a GNU extension
Note that variable length arrays are currently part of C, though not part of C++.
Oh, I didn't expect so many responses thank you guys. I'll start trying some different solutions here, it's just odd because I remember being able to do this before and not having any complications. I just switched to VS2010 from 2008 and I don't know if I like it too much lol
Ok it seems to just be a Visual Studio 2010 error, I've run my code in dev c++ and studio 2008 and I don't get so much as even a warning. I learned it that way but the new studio just won't let it go through, why is this? and is there any way to get it to work on here?
Quote:but the new studio just won't let it go through, why is this?
Did you read the responses? "The size of an array needs to be statically known" and "The compiler is right about showing an error, this is not legal."

Quote:is there any way to get it to work on here?
Either use a compiler that supports VLAs as an extension, in the process writing compiler specific code, or do what Concentrate said (the very first reply). You got 4 options there...
It's correct for this to be an error, you should not be able to do so, and I'm surprised it worked for you in Visual Studio 2008.

Why are you trying to use a char array? You're almost certainly better off using an std::string or an std::vector of chars.

- Jason Astle-Adams

This topic is closed to new replies.

Advertisement