Arrays in C
What are Arrays in C?
- Arrays are a fundamental data structure in C, allowing you to store multiple elements of the same data type in a next or together in memory space.
- This guide will cover one-dimensional (1D) and two-dimensional (2D) arrays.
- As well as essential concepts like strings, pointers, array-pointer relationships, pointer arithmetic, dynamic memory allocation, and more.
Array Declaration
- In C, you declare an array by specifying its data type, followed by the array name and the number of elements it can hold within square brackets.
- The general syntax for declaring an array is as follows:
1data_type array_name[array_size];
Here's what each part of the declaration means:
- data_type: This is the data type of the elements that the array will hold. It can be any valid C data type, such as int, char, float, etc.
- array_name: This is the name you give to the array, which allows you to refer to and manipulate the array later in your code.
- array_size: The number of elements the array can hold. This size must be an integer value, and it defines how many elements the array can store.
For example, if you want to declare an integer array that can store 5 elements, you would do it like this:
1int myArray[5];
This declares an integer array named myArray with the capacity to hold 5 integer values.
You can later initialize and access these elements using their indices, which start from 0.
1#include <stdio.h>
2
3int main() {
4 int numbers[5]; // Declare an integer array with the name "numbers" and space for 5 elements.
5
6 char vowels[5]; // Declare a character array with the name "vowels" and space for 5 elements.
7
8 double prices[10]; // Declare a double array with the name "prices" and space for 10 elements.
9
10 return 0;
11}
12
In this example, we've declared three different arrays:
- numbers is an integer array that can hold 5 integer values.
- vowels is a character array that can hold 5 characters (like letters of the alphabet).
- prices is a double array that can hold 10 double-precision floating-point values.
These arrays are declared but not yet initialized with specific values.
You can later assign values to the elements within these arrays as needed in your code.
Types of Arrays in C
- One-Dimensional (1D) Arrays
- Two-Dimensional (2D) Arrays
1. One-Dimensional (1D) Arrays
Declaration
- To declare a 1D array, you specify the data type and the array's name, followed by the number of elements in square brackets.
1int myArray[5];
2// Declare an integer array with 5 elements Initialization
- You can initialize the array during declaration or later using a loop or explicitly specifying values.
2. Two-Dimensional (2D) Arrays
Declaration
- A 2D array is like a table with rows and columns.
- You specify the data type, array name, and dimensions in square brackets.
1int matrix[3][3]; // Declare a 3x3 integer 2D array
Initialization
You can initialize a 2D array similarly to 1D arrays, with nested loops for each row and column.
1 int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // Initialize during declaration
3. Strings
Declaration
Strings in C are essentially arrays of characters.
1char myString[] = "Hello, World!";
4. Pointers
Declaration
- Pointers are variables that store memory addresses.
- You declare a pointer with an asterisk (*) followed by the data type.
1int *ptr; // Declare an integer pointer
Relationship between Arrays and Pointers
- Arrays and pointers are closely related.
- An array name can be used as a pointer to its first element.
1int arr[3] = {1, 2, 3};
2int *ptr = arr; // Pointer points to the first element of arr
3
5. Pointer Arithmetic
Pointer arithmetic allows you to move through the elements of an array.
1int arr[3] = {1, 2, 3};
2int *ptr = arr;
3
4printf("%d\n", *ptr); // Prints 1
5ptr++; // Move to the next element
6printf("%d\n", *ptr); // Prints 2
7
6. Dynamic Memory Allocation
- Dynamic memory allocation allows you to allocate memory at runtime.
- The functions malloc, calloc, and realloc are used to allocate memory, and free is used to deallocate it.
1#include <stdio.h>
2#include <stdlib.h>
3
4int main() {
5 int *dynamicArray = (int *)malloc(5 * sizeof(int)); // Allocate memory for 5 integers
6
7 if (dynamicArray != NULL) {
8 // Initialize the allocated memory
9 for (int i = 0; i < 5; i++) {
10 dynamicArray[i] = i + 1;
11 }
12
13 // Deallocate the memory when done
14 free(dynamicArray);
15 } else {
16 printf("Memory allocation failed.\n");
17 }
18
19 return 0;
20}
7. Pointer to Arrays
You can use pointers to access elements of arrays, which is closely related to the relationship between arrays and pointers, as shown earlier.
1#include <stdio.h>
2
3int main() {
4 int myArray[] = {10, 20, 30, 40, 50}; // Declare and initialize an integer array
5 int *ptr = myArray; // Pointer to the array
6
7 printf("First element: %d\n", *ptr); // Access the first element using the pointer
8 printf("Second element: %d\n", *(ptr + 1)); // Access the second element
9
10 return 0;
11}
In this example, we declare an integer array myArray, and then we create a pointer ptr that points to the first element of the array. We use the pointer to access individual elements.
8. Array of Pointers
An array of pointers allows you to store multiple pointers, each pointing to a different data structure, such as an array or string.
1#include <stdio.h>
2
3int main() {
4 int num1 = 10, num2 = 20, num3 = 30;
5 int *ptrArray[3]; // Array of integer pointers
6
7 ptrArray[0] = &num1; // Store the address of num1 in the first element
8 ptrArray[1] = &num2; // Store the address of num2 in the second element
9 ptrArray[2] = &num3; // Store the address of num3 in the third element
10
11 for (int i = 0; i < 3; i++) {
12 printf("Value %d: %d\n", i + 1, *(ptrArray[i])); // Access values using array of pointers
13 }
14
15 return 0;
16}
Here, we declare an array of integer pointers, ptrArray, with space for three pointers. We then store the addresses of different integer variables in the elements of the array and use the array to access and print these values.
9. Pointers to Functions
Pointers to functions allow you to call functions dynamically. You can define a function pointer and use it to call different functions at runtime.
1#include <stdio.h>
2
3int add(int a, int b) {
4 return a + b;
5}
6
7int subtract(int a, int b) {
8 return a - b;
9}
10
11int main() {
12 int (*operation)(int, int); // Pointer to a function that takes two integers and returns an integer
13
14 operation = add; // Point to the add function
15 int result1 = operation(5, 3); // Call add(5, 3) using the pointer
16
17 operation = subtract; // Point to the subtract function
18 int result2 = operation(5, 3); // Call subtract(5, 3) using the pointer
19
20 printf("Result1: %d\n", result1);
21 printf("Result2: %d\n", result2);
22
23 return 0;
24}
In this code, we declare a pointer to a function that takes two integers and returns an integer. We then point this function pointer to different functions (add and subtract) and use it to call these functions dynamically.
10. Array of Pointers to Function
You can create arrays of pointers to functions, which is useful for implementing function tables and dynamically selecting functions to call based on program logic.
1#include <stdio.h>
2
3int add(int a, int b) {
4 return a + b;
5}
6
7int subtract(int a, int b) {
8 return a - b;
9}
10
11int multiply(int a, int b) {
12 return a * b;
13}
14
15int main() {
16 int (*operations[3])(int, int); // Array of pointers to functions
17
18 operations[0] = add; // Store the address of the add function
19 operations[1] = subtract; // Store the address of the subtract function
20 operations[2] = multiply; // Store the address of the multiply function
21
22 for (int i = 0; i < 3; i++) {
23 int result = operations[i](5, 3); // Call functions using the array of function pointers
24 printf("Result %d: %d\n", i + 1, result);
25 }
26
27 return 0;
28}