C arrays
Created By: chatGPT
C arrays are a collection of elements of the same type stored in contiguous memory locations. They allow for the efficient organization of data. For instance, if you want to manage multiple values of the same type, using an array is advantageous. The array can be declared by specifying the type of its elements followed by the array's name and the number of elements in square brackets.
int numbers[5]; // declares an array of integers with 5 elements
To initialize an array, you can do it at the time of declaration or later. Initialization can be done implicitly by providing values in curly braces or explicitly by assigning values to each index.
int numbers[5] = {1, 2, 3, 4, 5}; // initializes the array with values
int more_numbers[5];
more_numbers[0] = 10;
more_numbers[1] = 20; // initializing later
To access an element in an array, you use the index, which starts from 0. For example, the first element is at index 0, the second at index 1, and so on. Trying to access an index out of bounds can lead to undefined behavior.
int first = numbers[0]; // accesses the first element
int second = numbers[1]; // accesses the second element
Looping through an array is a common task. You can use a simple
for
loop to traverse the entire array and perform operations on each element.for (int i = 0; i < 5; i++) {
printf("Element at index %d is %d\n", i, numbers[i]);
}
You can also create multi-dimensional arrays in C, which are essentially arrays of arrays. This is useful for representing matrices or grids.
int matrix[3][4]; // declares a 3x4 two-dimensional array
int table[2][2] = {{1, 2}, {3, 4}}; // initializes a 2x2 matrix
The size of an array can be determined using the
sizeof
operator, which returns the total size of the array in bytes. Dividing this size by the size of an individual element type allows you to find the number of elements.int array_size = sizeof(numbers) / sizeof(numbers[0]); // calculates the number of elements in numbers
Arrays can be passed to functions, but note that they decay to pointers when passed, meaning the function will receive the address of the first element. You can also pass the size of the array to avoid out-of-bounds access.
void print_array(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
print_array(numbers, 5); // calls the function to print the array