Section 5 - Remarks on Arrays
8A.5.1 Arrays of Chars
Chars are just really short ints, remember? They just happen to have an alternate set of constants: besides 65 you can use the literal 'A'. besides 66, the literal 'B', etc. And we usually use the char literals, not the actual ASCII codes, which we usually don't even think about.
So we can create arrays of chars just like arrays of numbers:
int dog[5] = {1, 2, 3, 4, 5}; double seal[7] = { 1.1, 3, .002, -2, -5, 3, 999.999 }; char word[12] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0' };
The last example can be shortened because of its universality to:
char word[12] = "Hello World";
This is not a string, but a char array. Next week we will talk more about these creatures.
8A.5.2 The Array Name
Let's declare an array of 100 dogs:
double dog[100];
If dog[39] is a double, as I said it was, what is dog? Well, it's the array, that's for sure, but can we ever use the name without the brackets in a program, is it done often, and what does it mean?
The answer is yes, yes, and good question.
We've already seen that we can pass arrays to functions (methods) by using the array name without brackets. We usually have to also pass a second parameter, the size of the array, so the method knows how to control the array in loops. So array names are used sans brackets all the time.
But what does the identifier dog mean when we don't have brackets attached to it?
What dog means is this: the address of the location where the array is stored. Since you already know that the array is stored beginning with dog[0], this is the same as the address of the location where dog[0] is stored, or more succinctly, the address of dog[0].
One thing you can't do with the array as a whole is to assign it a value with a single statement. Common error:
float a[5] = { 1.1, 2.2, 3.3, 4.4, 5.5 }; float b[5]; b = a; /* ERROR */ /*** THE PRECEDING HAS BEEN AN ERROR ***/
We have to use a loop if we want to move the contents of one array into another.
However, if you wrap an array in a class as we will do in an upcoming example (Frequency), then objects of those classes can be assigned to one another in a single assignment between references.
And that's all I want to say for now. See you next time.