Table of Contents
Arrays in C are an essential data structure that allows you to store and manipulate a collection of elements of the same type. They provide a convenient way to work with a fixed-size sequence of values. In this post, we will cover 1-dimensional arrays, 2-dimensional arrays, passing arrays to functions, and array pointers, along with examples to illustrate their usage.
What are Arrays in C?
- Arrays are user defined data types that hold multiple variables of the same data type.
- The first element in the array is numbered 0 (zero).
- Before using an array, its type and dimension must be declared.
Here is a video introduction of arrays:
Declaring an array:
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows:
type arrayName [ arraySize ];
Initializing an Array
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
Both the above statements declare and initialize an array named ‘balance’, type double and size 5.
Accessing Elements of an Array
Once an array is declared, let us see how individual elements in the array can be referred. This is done with subscript, the number in the brackets following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. Thus, marks [2] is not the second element of the array, but the third.
int valueOfThirdElement = marks[2];
Memory Structure of Arrays in C:
The array elements reside next to each other in memory. Thus, if we know the memory location of the first element, we can access all the other elements as well by just incrementing the memory location by the size of the type of memory.
Testing the memory structure:
Here is an example code to test the memory locations of different members of an array:
#include <stdio.h> int main() { int arr[5] = {1, 2, 3, 4, 5}; int i; printf("Address of array arr: %p\n", arr); for (i = 0; i < 5; i++) { printf("Address of arr[%d]: %p\n", i, &arr[i]); } return 0; }
In this example, we declare an integer array arr
of size 5 and initialize it with values from 1 to 5. We then print the memory address of the array itself, followed by the memory addresses of its individual elements using a for loop.
When you run this code, you’ll get an output similar to this (note that the actual addresses will vary each time you run the program):
Address of array arr: 0x7fff81b0e8c0 Address of arr[0]: 0x7fff81b0e8c0 Address of arr[1]: 0x7fff81b0e8c4 Address of arr[2]: 0x7fff81b0e8c8 Address of arr[3]: 0x7fff81b0e8cc Address of arr[4]: 0x7fff81b0e8d0
As you can see, the memory addresses of the elements are contiguous, and the difference between each consecutive address is equal to the size of an integer (4 bytes in this example).
Note: The code above uses pointers. Pointers in C/C++ are very Easy – NerdyElectronics
Video to understand the memory layout of an array:
1-Dimensional Arrays in C:
A 1-dimensional array, also known as a vector or a simple array, is a linear collection of elements of the same type. Each element in the array can be accessed using an index, starting from 0 to the size of the array minus one.
Consider this example: There is a building with 100 rooms. Now, we want to store the area of each room. Here we can use an array of size 100 to store the areas.
int room_area[100];
room_area[0] stores the area of 1st room.
room_area[1] stores the area of the 2nd room.
…
room_area[99] stores the area of 100th room.
Here room_area is a 1-dimension array.
Here’s an example of declaring, initializing, and accessing elements in a 1-dimensional array:
#include <stdio.h> int main() { int numbers[5]; // Declare an integer array of size 5 // Initialize the array elements numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; // Access and print array elements for (int i = 0; i < 5; i++) { printf("%d ", numbers[i]); } return 0; }
Output:
10 20 30 40 50
2-Dimensional Arrays in C:
A 2-dimensional array is essentially an array of arrays. It allows you to organize data in a tabular format with rows and columns. In C, we declare a 2-dimensional array by specifying the number of rows and columns.
Let’s build on the building and room examples from 1-D array. There we had one building with 100 rooms. Now, let’s say there are 3 buildings with 100 rooms each. A total of 300 rooms. Declaring 300 variables will be a very tedious task. Here we can have a 2-dimension array, where, one dimension is the building and the other dimension is the room.
int room_area[3][100];
room_area[0][0] stores the area of 1st room in the 1st building.
room_area[0][1] stores the area of the 2nd room in the 1st building.
…
room_area[2][99] stores the area of 100th room in the 3rd building.
Here room_area is a 2-dimension array.
Here’s an example:
#include <stdio.h> int main() { int matrix[3][3]; // Declare a 2D array with 3 rows and 3 columns // Initialize the array elements matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3; matrix[1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6; matrix[2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9; // Access and print array elements for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; }
Output:
1 2 3 4 5 6 7 8 9
Passing arrays to functions in C:
In C, you can pass arrays to functions by either passing the array itself or using a pointer to the array. When passing an array, it decays into a pointer to its first element. Here’s an example of passing an array to a function:
#include <stdio.h> // Function to print array elements void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } } int main() { int numbers[] = {1, 2, 3, 4, 5}; int size = sizeof(numbers) / sizeof(numbers[0]); // Pass the array to the function printArray(numbers, size); return 0; }
Output:
1 2
Array Pointers:
Arrays in C are closely related to pointers. In fact, the name of an array is a pointer to its first element. This allows us to use pointers to access and manipulate array elements. Here’s an example:
#include <stdio.h> int main() { int numbers[] = {1, 2, 3, 4, 5}; int *ptr = numbers; // Pointer to the first element of the array // Access array elements using pointer arithmetic for (int i = 0; i < 5; i++) { printf("%d ", *ptr); ptr++; // Move the pointer to the next element } return 0; }
Output:
1 2 3 4 5
In the example above, we initialize a pointer ptr
to the first element of the array numbers
. By dereferencing the pointer with *ptr
, we can access the value of the current element. Then, we increment the pointer ptr
to move it to the next element.
Arrays and pointers have a close relationship in C, and understanding this relationship is crucial for working effectively with arrays.
Conclusion
In summary, arrays in C are versatile data structures that allow you to store and manipulate collections of elements. Whether it’s a 1-dimensional array, a 2-dimensional array, passing arrays to functions, or using array pointers, arrays provide powerful capabilities for managing and accessing data. By mastering arrays, you can efficiently handle complex data structures and solve a wide range of programming problems.
Hi, I’m Vivek, a Senior Embedded Innovation Specialist. I have been working on Embedded Systems and IoT for the past 11 years. I love to share my knowledge and train those who are interested. Nerdyelectronics.com was started out of this interest. You can read my full profile in this link.