Accessing Array Elements using Pointers in C

print-array-elements-using-pointer-in-c-programming-language

Accessing Array Elements using Pointers in C Program Description:

Write a Program to Access the array elements using pointers in c programming language. The program should accept an array and print array elements using pointers. To access the array’s elements, we will use standard pointer notation (by dereferencing the pointer) as well as pointer subscript notation.

Prerequisites:

It is recommended to know the basics of the C Pointers and C Arrays, So please go through the following tutorials learn more about these concepts.

Accessing Array Elements using Pointer in C Program:

Here is the program to access the array elements using pointers in c language. We have accessed the integer array heights elements using a pointer variable ptr.

As we can see from the above program, We started the program by creating an integer array named heights, Then we stored the address of the heights array in the integer pointer ptr.

int *ptr = heights;

Note that, We used the heights array. As the array name also holds the memory address of the first element of the array.

Then we used a for loop to iterate over the array elements and printed the elements using the pointer ptr with Index(i) (i.e *(ptr+i))

Program Output:

Let’s compile and run the program using your compiler.

access-array-elements-using-pointers-in-c-programming

The program properly printed the array elements on the console.

Get Array Elements using the Pointer subscript notation [ ] in C:

Similarly, We can also use the pointer variable with the subscript notation [ ] to get the array elements.

Here is the program for getting the array elements using the pointer subscript notation in c programming language.

Note that, We used the pointer subscript notation ptr[i] to get the array element at the index i.

Program Output:

Compile the program.

$ gcc arr-ptr-subscript.c

Run the program and observe the output.

As we can see from the above output, we are able to get the array elements values using the subscript notation(ptr[i])

Related Programs:

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

2 Responses

  1. […] Accessing Array Elements using Pointers in C […]

  2. […] Accessing Array Elements using Pointers in C […]

Leave a Reply