Assigning Values to Arrays

You can initialize arrays (assign values to them) in one of two ways. First, you can do it one element at a time. Second, you can assign all of the values when declaring the array (just as you can assign values to any variable when you declare it). Let's go over both approaches in more detail.

Assigning values to one element

Assigning values to array elements is similar to assigning values to any other variable: you use the assignment operator. The one distinct difference is that you must indicate the index to which the assigned value should apply. But first, a quick word about indexes in C.

Strange as it may seem, arrays in C are indexed beginning at 0. So the first element in an array called answers is answers[0]. The twentieth element would be found at answers[19]. Therefore, to assign a value to an array's first element, you would code something like

int answers[20];
answers[0] = 32;

Programmers commonly make one of two mistakes when using this syntax. The first is to refer to an index that does not exist:

int answers[20];
answers[20] = 32;

Although answers has 20 elements in it, the final element can be found at answers[19]. This is called an Off-By-One-Bug (OB1B) and can happen to the best of us.

The second common error is to inadvertently refer to the same index multiple times:

answers[4] = 100;
answers[4] = 212;

The end result of those two lines is that answers[4] now has the value of 212, because the second assignment overwrites the value assigned the first time. In the following example, an array will be populated, although nothing will be done with that array quite yet.

To assign a value to an array element

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 6.1):

/* quiz.c - Script 6.1 */
#include <stdio.h>
int main (void) {

Script 6.1. In this first incarnation, the application creates an array with three elements and assigns values to each of them.


3.
Create an array variable:

unsigned int answers[3];

This variable, called answers, will store three values. The values will each be a non-negative (which is to say, unsigned) integer. The values correspond to the right answers for three questions that this application will eventually ask the user.

4.
Assign the value to the first array element:

answers[0] = 6;

The first element in the array—which is the right answer to the first question—should have a value of 6. This is assigned using the assignment operator and by referring to the array's index. Because it's the first element, 0 is used as the index.

5.
Assign values to the remaining two array elements:

answers[1] = 1908;
answers[2] = 1985;

The process (Step 4) is repeated, assigning values to the second and third elements of the array.

6.
Complete the main function:

    return 0;
}

7.
Save the file as quiz.c, compile, and debug as necessary (Figure 6.1).

Figure 6.1. Compile the code as you would any C application, checking for errors. In this figure, the Build and Debug option is being selected in Xcode.


This application doesn't do anything yet, so there's no reason to execute it.

✓ Tips

  • Array elements may have some random value until you formally initialize them. Thinking in terms of arrays and your computer's memory, keep in mind that whatever was stored in that memory block previously will be the value of an element until you assign it something else.

  • Referring to an array element that does not exist (like answers[20] when the array only goes up to answers[19]) will normally cause unfortunate results during the program's execution. These results could range from simply using values from adjacent memory blocks to crashing the application.


Assigning values to an entire array

If you want to populate an array all at once, the easiest way is to do so when you declare it. This technique still uses the assignment operator, but you need to separate the values by commas within curly braces:

int grades[3] = {94, 82, 87};

In such a case, you don't even have to specify the length of the array as that will be determined by how many values it is assigned:

int grades[] = {94, 82, 87};

Let's rewrite the quiz example, populating the array when it's defined.

To populate an array in one step

1.
Open quiz.c (Script 6.1) in your text editor or IDE, if it is not already open.

2.
Change the array definition line to read as follows (Script 6.2):

unsigned int answers[] = {6, 1908,
 1985};

Script 6.2. It's very easy to create and populate an array in one step, provided you use the proper syntax.


This one-line command has the same effect of defining and assigning values to the array over the course of four lines (the declaration plus one line for each array element). This format is more concise, and you don't need to muck around with setting the array's size or referring to specific indexes.

3.
Delete the later lines where the array was previously populated.

Obviously, you no longer have to set values for each element. There is some merit, however, to retaining the comments (which indicate what each numeric value means) so that you don't have mysterious numbers in your code.

4.
Save the file as quiz2.c, compile, and debug as necessary (Figure 6.2).

Figure 6.2. Again, assuming that your compiler is up to standards and that you typed the code properly, you should not see compilation errors. This is the view using Dev-C++.


Again, there's no reason to run the application but you should still compile it to check for errors.

✓ Tips

  • You can specify a starting index when populating an array. For example,

    ratings[20] = {[10] = 8.9};
    

    assigns the value of 8.9 to the eleventh item in the array. This is new as of the C99 standard and is referred to as a designated initializer.

  • If for some reason you decide to use the syntax for indicating a starting point when assigning array values, subsequent values will be assigned to elements in order thereafter:

    ratings[20] = {[10] = 8.9, 23.4,
     54.2}
    

    This code assigns values to ratings[10], ratings[11], and ratings[12].


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset