C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
another variable happened to be defined immediately after name, that other variable’s
data will be overwritten if you try to store a too-long string in name.

If the initial array needs to be larger than the initial value you assign, specify a larger array size when
you define the array, like this:


Click here to view code image


char name[80] = "Italy"; /* Leaves lots of extra room */

Doing this makes room for a string much longer than Italy if you want to store a longer string in
name. For example, you might want to use gets() to get a string from the user that could easily be
longer than Italy.


Make your arrays big enough to hold enough values, but don’t overdo it. Don’t make your arrays
larger than you think you’ll really need. Arrays can consume a large amount of memory, and the more
elements you reserve, the less memory you have for your program and other variables.


You can initialize an array one element at a time when you define an array by enclosing the array’s
data elements in braces and following the array name with an equals sign. For example, the following
statement both defines an integer array and initializes it with five values:


Click here to view code image


int vals[5] = {10, 40, 70, 90, 120};

As a review, Figure 21.1 shows what vals looks like in memory after the definition. The numbers in
brackets indicate subscripts. No null zero is at the end of the array because null zeroes terminate only
strings stored in character arrays.


FIGURE 21.1 After defining and initializing the vals array.

Note

The first subscript of all C arrays begins at 0.

The following statement defines and initializes two arrays, a floating-point array and a double

Free download pdf