C Arrays
C - Arrays
Section titled “C - Arrays”An array is a fundamental data structure in C that stores a fixed-size, sequential collection of elements of the same data type. Think of it as a group of variables of the same type, stored contiguously (one after another) in memory, accessible via a common name and an index.
Instead of declaring separate variables like score1, score2, score3, ..., you can declare a single array variable, say scores, and access individual elements using an index: scores[0], scores[1], scores[2], ....
Key Characteristics:
- Fixed Size: The size of a standard C array must be determined at compile time and cannot be changed during runtime. (C99 introduced Variable Length Arrays, VLAs, but their use has limitations and potential risks).
- Homogeneous Elements: All elements within an array must have the same data type (e.g., all
int, allfloat, allchar). - Contiguous Memory: Array elements are stored in adjacent memory locations, allowing for efficient access.
- Zero-Based Indexing: The first element is accessed with index
0, the second with index1, and the last element of an array of sizeNis accessed with indexN-1.
Declaring Arrays
Section titled “Declaring Arrays”To declare an array, you specify the element type, the array name, and the number of elements (size) enclosed in square brackets []:
type arrayName[arraySize];arraySize must be an integer constant expression greater than zero. type can be any valid C data type.
Examples:
#define MAX_STUDENTS 50
// Declare an array of 10 integersint counters[10];
// Declare an array of 20 floating-point numbersfloat temperatures[20];
// Declare an array to hold grades for MAX_STUDENTSchar grades[MAX_STUDENTS];Initializing Arrays
Section titled “Initializing Arrays”Arrays can be initialized at the time of declaration using an initializer list enclosed in curly braces {}:
// Initialize an array of 5 doublesdouble balances[5] = { 1000.0, 2.0, 3.4, 7.0, 50.0 };
// Initialize an array of integersint sequence[6] = { 1, 1, 2, 3, 5, 8 };Important Initialization Rules:
- The number of initializers in
{}cannot exceed the declared array size. - Partial Initialization: If fewer initializers are provided than the array size, the remaining elements are automatically initialized to zero (for arithmetic types) or NULL (for pointers).
- Omitting Size: If you provide an initializer list but omit the array size, the compiler automatically determines the size based on the number of initializers.
// Partial initialization: first 3 elements initialized, last 7 are zero.int partial[10] = { 5, 10, 15 };
// Omitting size: compiler creates an array of size 4.char vowels[] = { 'a', 'e', 'i', 'o', 'u' }; // Size is 5
// String literal initialization (includes null terminator)char message[] = "Hello"; // Size is 6 ('H','e','l','l','o','\0')Accessing Array Elements
Section titled “Accessing Array Elements”Individual array elements are accessed using the array name followed by the element’s index in square brackets [].
Remember: The index of the first element is 0, and the last element is arraySize - 1.
Example:
int values[5] = { 10, 20, 30, 40, 50 };
int firstValue = values[0]; // Access first element (value is 10)int thirdValue = values[2]; // Access third element (value is 30)
values[4] = 99; // Modify the last element (index 4)
// Attempting to access values[5] would be an error (out of bounds)Crucial Warning: C does not perform automatic bounds checking on array accesses. Accessing an element outside the valid index range (e.g., array[-1] or array[arraySize]) leads to undefined behavior. This can cause crashes, corrupt data, or create serious security vulnerabilities (buffer overflows). It is the programmer’s responsibility to ensure all array accesses are within the valid bounds.
Example: Declaring, Initializing, and Accessing
Section titled “Example: Declaring, Initializing, and Accessing”#include <stdio.h>#include <stddef.h> // For size_t
#define ARRAY_SIZE 10
int main(void) { int numbers[ARRAY_SIZE]; // Declare an array of 10 integers size_t i; // Use size_t for array indices/sizes - standard practice
// Initialize elements using a loop printf("Initializing array...\n"); for (i = 0; i < ARRAY_SIZE; ++i) { numbers[i] = (int)(i * i); // Store squares: 0, 1, 4, 9... }
// Access and print each element's value printf("\nArray elements:\n"); for (i = 0; i < ARRAY_SIZE; ++i) { // Defensive check (optional but good practice in complex scenarios) if (i < ARRAY_SIZE) { printf("Element[%zu] = %d\n", i, numbers[i]); } else { printf("Error: Index %zu out of bounds!\n", i); // Handle error appropriately } }
return 0;}When compiled and executed, this produces:
Initializing array...
Array elements:Element[0] = 0Element[1] = 1Element[2] = 4Element[3] = 9Element[4] = 16Element[5] = 25Element[6] = 36Element[7] = 49Element[8] = 64Element[9] = 81Further Array Concepts
Section titled “Further Array Concepts”Arrays are a fundamental topic with more advanced aspects:
| Concept | Description |
|---|---|
| Multi-dimensional arrays | Arrays of arrays, used to represent tables or matrices (e.g., int matrix[3][4];). |
| Passing arrays to functions | When an array name is passed to a function, it ‘decays’ into a pointer to its first element. The size information is lost unless passed separately. |
| Returning arrays from functions | Functions cannot directly return entire arrays. Common techniques involve returning a pointer to a dynamically allocated array, returning a pointer to a static array (use with caution), or wrapping the array in a struct. |
| Pointers and Arrays | There’s a strong relationship between pointers and arrays in C. The array name itself often behaves like a pointer to the first element (e.g., arrayName is equivalent to &arrayName[0] in many contexts). |
| Variable Length Arrays (VLAs) | Introduced in C99, allow array size to be determined at runtime. Declared like int arr[n]; where n is a variable. Became optional in C11/C17/C23. Can risk stack overflow if n is large. Use with caution; dynamic allocation (malloc) is often safer for runtime-sized arrays. |
These topics are typically covered in more detail in subsequent chapters or tutorials.