access array using pointer code example

Example 1: accessing elements of 1d array using pointers

#include<stdio.h>

int main(){

    int arr[] = {1,3,4,5,6,7,8};
    int *ptr = &arr; //storing address of the first element in array in the ptr

  	//accessing the elements of the array using ptr
    for(int i=0;i<7;i++)
        printf("%d ",*(ptr+i));
  	//here i represents the value to be added to the base address
    return 0;
}

Example 2: how to print a pointer array in c

#include <stdio.h>
int main() {
    int data[5];

    printf("Enter elements: ");
    for (int i = 0; i < 5; ++i)
        scanf("%d", data + i);

    printf("You entered: \n");
    for (int i = 0; i < 5; ++i)
        printf("%d\n", *(data + i));
    return 0;
}

Tags:

Misc Example