Skip to main content

Chapter Summary

This chapter introduces arrays, a fundamental data structure that allows programs to store and manage multiple elements of the same type. Arrays are essential for handling collections of data efficiently, eliminating the need to declare separate variables for each data item.

Key Concepts

Arrays

  • Declaration: datatype arrayName[capacity]; reserves space for a fixed number of elements
  • Indexing: Elements are accessed using zero-based indices (0 to capacity-1)
  • Initialization: Arrays should be initialized using {0} to set all elements to zero, preventing undefined values
  • Capacity vs. Used: Capacity is the total space reserved; used is the number of elements actually storing meaningful data
  • Bounds Checking: C does not automatically check array bounds; accessing elements outside the valid range causes serious errors
  • When arrays are passed to functions, the function receives the original array, not a copy
    • Any modifications to an array parameter within a function modify the original array
    • Use the const keyword in function parameters to prevent accidental modification: void function(const int array[], int used)
  • Iteration: Loops through entire array containing used values: for (i = 0; i < used; i++)

C-Strings

  • Definition: Null-terminated character arrays where the null character \0 marks the end of the string
  • Declaration: Must account for the null terminator; a 15-character string requires char str[16]
  • Initialization: String literals automatically include the null terminator: char greeting[20] = "Hello"; is equivalent to char greeting[20]={'H','e','l','l','o','\0'};
  • Reading Strings: Use scanf("%s", str) to read a word (stops at whitespace)
  • Iteration: Loop until reaching \0: for (i = 0; str[i] != '\0'; i++)
Critical C-String Requirement

The null terminator \0 is mandatory for C-strings. Overwriting or omitting it causes crashes and security vulnerabilities. Always allocate one extra byte for the null terminator when declaring strings.

Common Patterns

Iterating Through an Array with Known Used Elements

Allows you to process each element of the array

int i;
for (i = 0; i < used; i++) {
// process array[i]
}

Iterating Through a String

Allows you to to process each character of the string

int i;
for (i = 0; str[i] != '\0'; i++) {
// process str[i]
}