Access Array Using Pointer in C

Access Array Using Pointer:

On this page we will discuss about access array using pointer in C language and write a program for it.This will help to understand the basic structure of arrays and pointers.We can understand pointer as an variable which holds the address of another variable.

Access Array Using Pointers in C

Access Array Using Pointer in C Language

  • Array is collection of data items of homogeneous types at contiguous memory location.
  • Pointer is itself a variable which holds the address of another variable.
  • Array can be initialized at declaration where as pointer can’t be initialized at declaration.We can access the array elements using pointer.
  • Pointer to array means the pinter variable will hold the address to the first element of array of base element of array let’s say p[0] where a is an array.
  • If we use * before pointer variable it will return the value store at the address.

Example:

int p[5] = {8, 9, 10, 11, 12};
int *ptr  = p
Accessing Array Using Pointer in C Programming-2

Program 1:

Run

#include <stdio.h>

int main ()
{
  int p[5] = { 8, 9, 10, 11, 12 }, i;
  int *ptr = p;

  for (i = 0; i < 5; i++)
    printf ("&p[%d] = %p \t p[%d] = %d\n", i, ptr + i, i, *(ptr + i));

  return 0;
}

Output:

&p[0] = 0x7ffeafbc9190	 p[0] = 8
&p[1] = 0x7ffeafbc9194	 p[1] = 9
&p[2] = 0x7ffeafbc9198	 p[2] = 10
&p[3] = 0x7ffeafbc919c	 p[3] = 11
&p[4] = 0x7ffeafbc91a0	 p[4] = 12
 

Program 2:Modifying Elements of Array  Using Pointer

Run
#include<stdio.h>

int main ()
{
  int p[5] = { 8, 9, 10, 11, 12 }, i;
  int *ptr = p;
  *(ptr+3) = 16;

  for (i = 0; i < 5; i++)
    printf ("&p[%d] = %p \t p[%d] = %d\n", i, ptr + i, i, *(ptr + i));

  return 0;
}
//4th element is modified from 11 to 16

Output:

&p[0] = 0x7ffef151f3c0	 p[0] = 8
&p[1] = 0x7ffef151f3c4	 p[1] = 9
&p[2] = 0x7ffef151f3c8	 p[2] = 10
&p[3] = 0x7ffef151f3cc	 p[3] = 16
&p[4] = 0x7ffef151f3d0	 p[4] = 12

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription