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

(Romina) #1

21. Dealing with Arrays


In This Chapter


  • Reviewing arrays

  • Putting values in arrays


The really nice thing about this chapter is that it covers absolutely nothing new. You’ve already
worked with arrays throughout the book when storing strings in character arrays. This chapter simply
hones that concept of arrays and demonstrates that you can create an array of any data type, not just the
char data type.


As you know, an array of characters is just a list of characters that has a name. Similarly, an array of
integers is just a list of integers that has a name, and an array of floating-point values is just a list of
floating-point values that has a name. Instead of referring to each of the array elements by a different
name, you refer to them by the array name and distinguish them with a subscript enclosed in brackets.


Reviewing Arrays


All arrays contain values called elements. An array can contain only elements that are of the same
type. In other words, you can’t have an array that has a floating-point value, a character value, and an
integer value.


You define arrays almost the same way you define regular non-array variables. To define a regular
variable, you only have to specify its data type next to the variable name:


Click here to view code image


int i; /* Defines a non-array variable */

To define an array, you must add brackets ([]) after the name and specify the maximum number of
elements you will ever store in the array:


Click here to view code image


int i[25]; /* Defines the array */

If you want to initialize a character array with an initial string, you know that you can do this:


Click here to view code image


char name[6] = "Italy"; /* Leave room for the null! */

Warning

After you define an array to a certain size, don’t try to store more elements than were
allowed in the original size. After defining name as just done, the strcpy()
function lets you store a string longer than Italy in name, but the result would be
disastrous because other data in memory could be overwritten unintentionally. If
Free download pdf