accessing elements of 1d array using pointers

To access elements of a 1D array in C using pointers, you can follow these steps:

  1. Declare a pointer variable of the same type as the array.
  2. Assign the address of the first element of the array to the pointer variable.
  3. Use pointer arithmetic to access the elements of the array.

Here's an example:

#include <stdio.h>

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int *ptr = arr; // Step 1: Declare a pointer variable and assign the address of the first element of the array to it

    for (int i = 0; i < 5; i++) {
        printf("%d ", *(ptr + i)); // Step 3: Access the elements of the array using pointer arithmetic
    }

    return 0;
}

In the example above, we declare an array arr of size 5 and initialize it with some values. Then, we declare a pointer variable ptr and assign the address of the first element of arr to it. Inside the for loop, we use pointer arithmetic to access the elements of the array by dereferencing the pointer ptr and adding the index i to it.

The output of the program will be: 1 2 3 4 5, which are the elements of the array arr.

That's how you can access elements of a 1D array using pointers in C.