Printing Array values using pointers

Learn how to print array values using pointers in C programming language

In this C programming language example of pointers and array we will print out array values using pointers. Pointers and array are very closely related. One fact is that the an array pointers points to the base address or the starting address of the array. So one can optionally not create a new pointer but just use the indirection operator * to access the elements of an array. An example will be shown shortly below.

Consider an array called arr:

To print out the values of this array we can use for loop and indexing to access the elements of the array as follows.

The following example now shows how pointers to array can be used to print the array elements. First we create a pointer ptr to the the array. Then using for loop we print out the elements using the pointer with indirection operator. Notice that we have to increment the pointer by 1 to get the value of the next address pointed by the pointer in the for loop.

Both of the above two programs are the same and produces the same result.

But now looking at the difference and similarly of the above programs, we can see that the creating a new pointer ptr is unnecessary for the array. We can just use the indirection operator * with the array arr to print out the array elements.

So these examples showed you how to print array elements by creating a new pointer to the array and also without creating a new pointer. See Easy to understand Pointer in C and Difference between function call by value and call by reference examples of pointers.

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Leave a Reply

Your email address will not be published. Required fields are marked *

Difference between function call by value and call by reference

Pass an entire array to a function using Pointers