Can I declare an array variable as "int a[]", as in an array with no specified amount of elements to hold initially (to be determined later with a index variable)? I am writing a program that relies on a file whose contents are read into the array, but the file's contents can vary, so I'm curious if I can do this, and then determine through a file read how many elements are in the file, then take that number and use it as the amount of the array's index.

Or maybe I got it all in reverse, and that maybe I have to do the file read FIRST, then when declaring the array to hold its contents, I use the counted contents index in the array declaration?
I.E: int a[index];

Thanks in advance


Recommended Answers

All 2 Replies

My C++ is slightly rusty, but I'll give this a shot anyway:

No, you cannot declare an array as

int a[];

The reason for this is because the size of "a" (number of elements it can contain) is decided at compile time when declared like that.

You can also not do something like:

int index;
//figure out how many items are in the file
index = getNumberOfItemsInFile();
int a[index];

And basically the reason is the same as before: "index" is variable, so at compile time the compiler does not know its value, and thus cannot determine how big "a" needs to be. The compiler then complains.

If you need to store items in a variable-length list, why don't you just use the STL <list> (or similar container, depending on your needs), or if you're using a proprietary compiler (e.g. Borland C++), you can use their libraries (for Borland, it will be the TList class, and I'm sure MS Visual C++ has something similar).


You can use a pointer , then allocate n amount of Int

not sure if I can post you the code but i'll show it to you anyway:

int* a; //make a pointer to int

//run your code to get "index"
a= new int[index];
//use a[index] as your array

//don't forget to free the memory pointing to variable a
//after you finished with it
//use "delete [] a"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.