
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 on 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:
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:
int myArray[5];
This declares an integer array named myArray that can hold 5 integer values.
You can later initialize and access these elements using their indices starting from 0.
#include <stdio.h>
int main() {
int numbers[5]; // Declare an integer array with the name "numbers" and space for 5 elements.
char vowels[5]; // Declare a character array with the name "vowels" and space for 5 elements.
double prices[10]; // Declare a double array named "prices" and space for 10 elements.
return 0;
}
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 design values to 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.
int myArray[5];
// Declare an integer array with 5 elements Initialization
You can initialize that 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.
int 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.
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.
char 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.
int *ptr; // Declare an integer pointer
Relationship between Arrays and Pointers
- Arrays and Pointers are close.
- An array name can be used as a pointer to its first element.
int arr[3] = {1, 2, 3};
int *ptr = arr; // Pointer points to the first element of arr
5. Pointer Arithmetic
Pointer arithmetic allows you to move through the elements of an array.
int arr[3] = {1, 2, 3};
int *ptr = arr;
printf("%d\n", *ptr); // Prints 1
ptr++; // Move to the next element
printf("%d\n", *ptr); // Prints 2
6. Dynamic Memory Allocation
- Dynamic memory allocation allows you to allocate memory at runtime.
- Malloc, calloc, and realloc are used to allocate memory, and free is used to deallocate it.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *dynamicArray = (int *)malloc(5 * sizeof(int)); // Allocate memory for 5 integers
if (dynamicArray != NULL) {
// Initialize the allocated memory
for (int i = 0; i < 5; i++) {
dynamicArray[i] = i + 1;
}
// Deallocate the memory when done
free(dynamicArray);
} else {
printf("Memory allocation failed.\n");
}
return 0;
}
7. Pointer to Arrays
You can use pointers to access elements or arrays, which is closely related to the relationship between arrays and pointers, as shown earlier.
#include <stdio.h>
int main() {
int myArray[] = {10, 20, 30, 40, 50}; // Declare and initialize an integer array
int *ptr = myArray; // Pointer to the array
printf("First element: %d\n", *ptr); // Access the first element using the pointer
printf("Second element: %d\n", *(ptr + 1)); // Access the second element
return 0;
}
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 Pointer
An array of pointers allows you to store multiple pointers, each pointing to a different data structure, such as an array or string.
#include <stdio.h>
int main() {
int num1 = 10, num2 = 20, num3 = 30;
int *ptrArray[3]; // Array of integer pointers
ptrArray[0] = &num1; // Store the address of num1 in the first element
ptrArray[1] = &num2; // Store the address of num2 in the second element
ptrArray[2] = &num3; // Store the address of num3 in the third element
for (int i = 0; i < 3; i++) {
printf("Value %d: %d\n", i + 1, *(ptrArray[i])); // Access values using array of pointers
}
return 0;
}
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 decline a function pointer and use it to call different functions at runtime.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int main() {
int (*operation)(int, int); // Pointer to a function that takes two integers and returns an integer
operation = add; // Point to the add function
int result1 = operation(5, 3); // Call add(5, 3) using the pointer
operation = subtract; // Point to the subtract function
int result2 = operation(5, 3); // Call subtract(5, 3) using the pointer
printf("Result1: %d\n", result1);
printf("Result2: %d\n", result2);
return 0;
}
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.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
int (*operations[3])(int, int); // Array of pointers to functions
operations[0] = add; // Store the address of the add function
operations[1] = subtract; // Store the address of the subtract function
operations[2] = multiply; // Store the address of the multiply function
for (int i = 0; i < 3; i++) {
int result = operations[i](5, 3); // Call functions using the array of function pointers
printf("Result %d: %d\n", i + 1, result);
}
return 0;
}