From the course: C: Data Structures, Pointers, and File Systems

Understanding arrays - C Tutorial

From the course: C: Data Structures, Pointers, and File Systems

Start my 1-month free trial

Understanding arrays

- [Instructor] In this code you see five float variables, each of which holds a high score value and is named appropriately. Build and run. And nothing surprising. Back in the code, I hope you see how this type of declaration is inefficient. Lines 14 through 18 repeat, there must be a better way. In C, an array is a collection of consecutive objects, all of the same data type, that's the short definition. Specifically, an array is a variable. It's declared like any variable given a data type variable name but the name is followed by square brackets. A value within the brackets indicates the number of items or elements within the array. This array is declared for five elements, each of a float data type. This is a better way to store five high score values shown earlier in the exercise file. Like any variable, you can initialize an array. To do so, follow the declaration with an assignment operator equals, then set the values assigned to each element within braces, separated by commas. And when you assign values in this manner, you can omit the number of elements from the declaration. The compiler figures out the value on its own. Elements in an array are addressed individually in this format, the array name and element number in brackets. Here an array element is assigned a value just like any other variable. The value in brackets represents the element number. This value can be expressed as a constant, as shown here, or it can be a variable or invalid expression. And it's important to remember that the first element of the array is always zero. This array has five elements, they are numbered zero, one, two, three, and four. Variable high score two is the third element in the array. This numbering scheme is something you'll probably forget. Even I mess up element numbers on occasion. Finally, here are some array trivial tidbits. Arrays in C are non-dynamic, you cannot alter their size as a program runs. Therefor, you must get the size correct when the array is declared, and as an aside, it's possible to declare an arrays length as the program runs, but most programmers avoid this practice, just set the value in your code and know that it cannot be increased when the program is running. The C language does no bounds checking for an array. It's possible to reference an element outside the array's declaration. Doing so gets you into trouble. And arrays are closely related to pointers, and they're similar in many respects, but array notation is not a shorthand for pointer notation. The topic of pointers is covered elsewhere in this course.

Contents