tags:

views:

309

answers:

4

I'm trying to initialize the last element in the array

int grades[10];

to grade 7 but it doesn't seem to work

I'm using C++ btw

+1  A: 

The last element is grades[9], since arrays in C++ are zero-based (e.g. grades[0] to grades[9] are 10 elements). Is that what you're doing?

You might need to subtract one from the grade to use as your subscript value, or set the extent to one more.

lavinio
+1  A: 

Remember that an array with ten elements will have grades[0] through grades[9], and that grades[10] is an error.

Aric TenEyck
+8  A: 

If you want to initialize them all at definition:

int grades[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 7 };

If you want to initialize after:

int grades[10];
grades[9] = 7;

But, be aware that grades 0..8 will still be uninitialized, and will likely be junk values.

tfinniga
Thanks, I forgot that the ninth element was the last one =) thank you
if you were assigning to grades[10] that's called an "off by one" error. That is memory that grades doesn't own and you may have corrupted something else in the function/program.http://en.wikipedia.org/wiki/Off-by-one_error
jinxx0r
yeah thank you very much, I knew about this but I've never really used it while coding.. I won't forget it from now on!
You're incorrect in that the "ninth" one is last. If you have ten elements, the tenth one is the last one. The thing is that they are numbered 0 through 9, so your tenth element is accessed by the number 9.
GMan
@tfinniga: You mean _definition_, not _declaration_, since `int grades[10];` _defines_ the array.
sbi
@sbi thanks, fixed
tfinniga
+3  A: 

One more thing, if you initialize only the first element (if explicit array size is specified) or a shorter initiliazation list, the unspecified elements are fill with 0. E.g.

int grades[10] = {8}; //init with one element

is the same as:

int grades[10] = { 8, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

or

int grades[10] = { 1, 9, 6, 16 }; //or init with a shorter than array size list with a minimum of 1 element

is the same as:

int grades[10] = { 1, 9, 6, 16, 0, 0, 0, 0, 0, 0 };

I find it handy for initializing an array with 0 values.

float coefficients[10] = {0.0f}; //everything here is full of 0.0f
Stringer Bell
Note that it is valid C++ to write: `int a[10] = {};`.
GMan