Can we access the array using a pointer in C language?

Fill In The Blank
Views 740

Answer:

Yes, by holding the base address of array into a pointer, we can access the array using a pointer.

Yes, it is possible to access an array using a pointer in C language. A pointer is a variable that stores the memory address of another variable. In the case of arrays, a pointer can be used to store the memory address of the first element of the array.

Here is an example of how to access an array using a pointer in C language:


#include <stdio.h>

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

    printf("Array elements: ");
    for(int i = 0; i < 5; i++) {
        printf("%d ", *(ptr + i));
    }
    return 0;
}

In this example, the array arr is initialized with the values 1, 2, 3, 4, 5. The pointer ptr is assigned the memory address of the first element of the array. The for loop is used to traverse the array using the pointer. The * operator is used to dereference the pointer and access the value stored at that memory address. The output of this program will be "Array elements: 1 2 3 4 5".

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of C Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.