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

C Programming Language >   Pointer in C Language >   Pointer and Array  

Long Question

843


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".


This Particular section is dedicated to Question & Answer only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.