Declaring and Initializing Arrays and Pointers
In this step, we will learn how to declare an array and a pointer, which are the fundamental components for array traversal using pointers.
Understanding Arrays and Pointers
An array in C is a collection of elements of the same type stored in contiguous memory locations. For example, an integer array with 5 elements will reserve space for 5 integers in memory, one after another.
A pointer is a variable that stores the memory address of another variable. We can use pointers to indirectly access the value stored at a particular memory address.
Let us modify our main.c
file to include an array and a pointer:
#include <stdio.h>
int main() {
printf("Array Traversal using Pointers\n\n");
// Declare and initialize an array of 5 integers
int arr[5] = {10, 20, 30, 40, 50};
// Declare a pointer of integer type
int *ptr;
// Print the array elements using array notation
printf("Array elements using array notation:\n");
for(int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
In this code:
- We declared an integer array
arr
with 5 elements and initialized it with values 10, 20, 30, 40, and 50.
- We declared an integer pointer
ptr
which will be used later to point to the array elements.
- We printed the array elements using traditional array notation.
Compile and run the program to see the array elements:
gcc main.c -o main
./main
You should see the following output:
Array Traversal using Pointers
Array elements using array notation:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50
In the next step, we will connect the pointer to the array and access array elements using the pointer.