Click to See Complete Forum and Search --> : initialize an entire array


frelon102
February 4th, 2003, 03:14 PM
Hi,

I have an array of 300 X 7 declared in the main() and I need to initialize each data in another function like:
array[0][0] = 2;
array[0][1] = 10;
array[0][2] = 4;
and so on...

I tried to initialize the entire array at the time, but it doesn't work: array = {{2,10,4,..},{...},...} seems to work only with the array declaration.

Is there a way to avoid writing 2100 rows of code for the assignation ?

Note: I use C for programming, and not for running under windows, but I think it's a general C question.

Thanks,
Frelon102

PaulWendt
February 4th, 2003, 04:40 PM
If there's a formula for how you're going to be initializing the
elements of the array, then you could use that formula. For
example, if you wanted each element to be its index * 2, you'd:

for (int i = 0; i < NUM_ELEMENTS; ++i)
{
theArray[i] = i * 2;
}


That's very simplistic and your array is more complex, I realize,
but it could give you an idea.

Typically, however, the above scenario doesn't exist in the real
world very often. What probably would happen is that you'd want
to initialize your data and one option is to initialize it from a file.
You could then alter the array's contents by modifying the file
and leaving the program alone. Of course, a weakness of this
approach is that reading a file and putting its contents in memory
will be a little slower than having the compiler initialize your
elements for you :)

Oh, your assertion that the initializer list is only valid at the point
of declaration is correct.

--Paul