Arrays and Pointers in C

In C programming language, arrays and pointers are closely related. In fact, an array can be thought of as a pointer to the first element of the array.

When an array is declared, the name of the array is actually a pointer to the first element of the array. Here’s an example of how to declare and initialize an array in C:

int arr[] = {1, 2, 3, 4, 5};

In this example, we declare an integer array named “arr” and initialize it with the values 1 through 5. The name “arr” is actually a pointer to the first element of the array.

We can use pointer arithmetic to access the elements of an array using a pointer. Here’s an example of how to access the elements of an array using a pointer:

int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to the first element of the array

printf("%d\n", *ptr); // prints 1
printf("%d\n", *(ptr + 1)); // prints 2
printf("%d\n", *(ptr + 2)); // prints 3

In this example, we declare an integer array named “arr” and a pointer named “ptr” that points to the first element of the array. We then use pointer arithmetic to access the elements of the array by adding an offset to the pointer.

We can also use pointer arithmetic to pass an array to a function. When an array is passed to a function, it is actually passed by reference as a pointer to the first element of the array. Here’s an example of how to pass an array to a function:

void print_array(int *arr, int size) {
    int i;
    for (i = 0; i < size; i++) {
        printf("%d ", *(arr + i));
    }
    printf("\n");
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = 5;

    print_array(arr, size);

    return 0;
}

In this example, we declare an integer array named "arr" and a variable named "size" that represents the size of the array. We then define a function named "print_array" that takes a pointer to an integer array "arr" and the size of the array "size" as arguments. The function uses pointer arithmetic to print the elements of the array.

In the main function, we call the "print_array" function and pass the "arr" array and the "size" variable as arguments.

Arrays and pointers are closely related in C programming language. By understanding how arrays and pointers work together, we can write more efficient and flexible programs.