Click to See Complete Forum and Search --> : Defining array with variables


NaveedAnis
December 10th, 2001, 07:23 AM
The following lines of code does not compile:
int size=5;
char data[size];


I have running code in linux that says:

int size=5;
char data[size];
but on windows, it gives compilation error.

Can anyone suggest a solution to it?

Andreas Masur
December 10th, 2001, 08:06 AM
const int size = 5;
char data[size];



The size of an array needs to be a constant value...

Ciao, Andreas

"Software is like sex, it's better when it's free." - Linus Torvalds

NMTop40
December 10th, 2001, 08:15 AM
if you know that size is 5 why do you need to put size as the size of data like this;

char data[5];

But you can do it in several ways. Some compilers will allow


const int size=5;
char data[size];




They all should, but I think VC++ doesn't.

You can also do


#define size 5 // not preferred
char data[size];




or

enum { size=5 };
char data[size];




if you don't know size in advance, you need to allocate data on the heap like this:

char * data = new char[size];



and later you must delete it yourself with

delete data;



However standard C++ offers a nice template class that avoids the problem. You can define

std::vector<char> data(5, '\0' );



This will create you a vector of 5 characters, all initialized to the zero character.

If you want to use your data to store a string, it is better still to use std::string thus

std::string data;



It won't have a size of 5 though. It will be able to resize automatically as it needs to.

Paul McKenzie
December 10th, 2001, 09:33 AM
NMTop40 answered your question, but I would like to add that those lines are not ANSI C or ANSI C++ compliant and are invalid. The code will fail on any other compiler, even other Linux compilers. The Windows compiler (and any other compliant compiler) should give you an error. I'm sure that there is a switch on your Linux compiler command line that says to "compile in ANSI mode" or "turn off extensions". Once you use this switch, you will see that even the Linux compiler you are using now will give you an error.

Once you get the Windows compiler to work, maybe you should go back and fix the Linux code so that it is also valid code.

Regards,

Paul McKenzie