Monday, August 17, 2009

c++ array:

However, when doing array declarations, the size of the array must be a constant.
view source
print?
01.int anArray[5]; // Ok -- 5 is a literal constant
02.
03.#define ARRAY_SIZE 5
04.int anArray[ARRAY_SIZE]; // Ok -- ARRAY_SIZE is a symbolic constant
05.
06.const int nArraySize = 5;
07.int anArray[nArraySize]; // Ok -- nArraySize is a variable constant
08.
09.enum ArrayElements
10.{
11. MAX_ARRAY_SIZE = 5;
12.};
13.int anArray[MAX_ARRAY_SIZE]; // Ok -- MAX_ARRAY_SIZE is an enum constant
14.
15.int nSize = 5;
16.int anArray[nSize]; // Not ok! -- nSize is not a constant!

To summarize, array elements can be indexed with constants or non-constants, but arrays must be declared using constants. This means that the array’s size must be known at compile time!

Arrays can hold any data type, including floating point values and even structs:
view source
print?
01.double adArray[5]; // declare an array of 5 doubles
02.adArray[2] = 7.0; // assign 7.0 to array element 2
03.
04.struct sRectangle
05.{
06. int nLength;
07. int nWidth;
08.};
09.sRectangle asArray[5]; // declare an array of 5 sRectangle

To access a struct member of an array element, first pick which array element you want, and then use the member selection operator to select the member you want:
view source
print?
1.// sets the nLength member of array element 0
2.asArray[0].nLength = 24;

Elements of an array are treated just like normal variables, and as such have all of the same properties.





Consequently, to initialize all the elements of an array to 0, you can do this:
view source
print?
1.// Initialize all elements to 0
2.int anArray[5] = { 0 };

Omitted Size

If you are initializing an array of elements using an initializer list, the compiler can figure out the size of the array for you, and you can omit explicitly declaring the size of the array:
view source
print?
1.int anArray[] = { 0, 1, 2, 3, 4 }; // declare array of 5 elements

Sizeof

The sizeof operator can be used with arrays. It returns the total size allocated for the entire array:
view source
print?
1.int anArray[] = { 0, 1, 2, 3, 4 }; // declare array of 5 elements
2.cout << sizeof(anArray); // prints 20 (5 elements * 4 bytes each)
In C++, there is no direct way to ask an array how many elements it contains. However, using the sizeof operator, we can figure it out:
view source
print?
1.int nElements = sizeof(anArray) / sizeof(anArray[0]);
Because all of the elements of the array have the same size, dividing the total size of the array by the size of any one of the elements yields the number of elements in the array! We use element 0 because it is the only element guaranteed to exist, as arrays must have at least one element.

Arrays and Enums

No comments:

Post a Comment