Initializing Arrays

[Pages:5]Initializing Arrays

--------------------------------------------Section #1: Initializing Arrays (p.388) ---------------------------------------------

We've spent a lot of time discussing the effects of initialization, where space is not only allocated for a variable, but it simultaneously gives it a defined value so that the variable is "born" with a defined value (e.g., initializing local variables, global variables, formal parameters, etc.). So how about arrays? Can those be initialized too? You betcha!

First let's look at the initialization of a simple integer variable:

int

intVal;

This would allocate space for the variable 'intVal' which would be capable of storing a single integer value:

+-----+

|

|

intVal [0x220] | ??? |

|

|

+-----+

Notice that it doesn't have a defined value, the variable declaration simply allocated the space in memory where we can later store an integer value. But of course, we can initialize the variable like this:

int

intVal = 63;

Now we not only get the variable allocated, but it's also "born" with a defined value of 63:

+-----+

|

|

intVal [0x220] | 63 |

|

|

+-----+

The syntax for that variable declaration is this:

= ;

So the data type is "int", the identifier is "intVal" and the initializer is 63.

Well, arrays follow a similar syntax, except when we create an array we're not just allocating space in memory for a single value, but a contiguous block of values, so we can't have a simple initializer, instead we use what's called an initialization list. What's an initialization list?

An initialization list is a comma-delimited list of initializers, enclosed in a pair of open/close curly braces.

The syntax to initialize an array is this:

[] = {};

Let's try it out! Here's an array of five ints:

int myInts[5];

If you do that, what do you get in return? You get memory allocated that looks like this:

+-----+

|

|

myInts [0x100] | ??? | [0] ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download