Beginner's question on Arrays

Can I write 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 initializer.
I.E: int a[index];
Can I write 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)?


No.

Arrays must have a size determined immediately:

1
2
3
4
5
6
7
int main()
{
  int foo[];  // Error -- no size
  int bar[5]; // OK, size is 5
  int baz[] = {1,2,3};  // OK, size can be determined by number of
     // elements in the {braces}, so size is 3
}


The only other time empty brakets are acceptable is when you pass it to a function. And in that event, you're not really passing an array, but are passing a pointer:

1
2
3
void func(int param[])  // this

void func(int* param)  // is the same as this 


EDIT:
As for your problem (needing an array that grows), consider using a vector. They're basically resizable arrays:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <vector>

int main()
{
  std::vector<int> foo;  // an array of size 0

  foo.push_back(5);  // puts '5' at the end of the array, increasing the size to 1
  foo.push_back(3);  // size=2

  foo.resize(10);  // size=10

  foo.pop_back();  // drop last element.  size=9

  cout << foo.size();  // prints '9'

  cout << foo[1];  // prints '3' (element [1], just like an array) 


EDIT2:

Also...
int a[index];


You can't do this unless 'index' is a constant. The way to determine the size of the array at runtime would be to dynamically allocate it (with new[]). But it's safer and easier to just use a vector as illustrated above.
Last edited on
Topic archived. No new replies allowed.