C Tutorial
This c program is to get all the array elements from last index to first index using pointers.
Initialized interger pointer ptr and assigned array last element reference, decrements pointer in each iteration till reading first array element.
#include<stdio.h> void main() { int arr_list[] = {10, 8, 6, 4, 2, 1}; int *ptr; for(ptr=&arr_list[5];ptr>=arr_list;ptr--) { printf("%d\t", arr_list[ptr-arr_list]); } }
Output:
$ cc array-traversal.c $ ./a.out 1 2 4 6 8 10
default array name provides the address of last array element instead of using &array_name[end_index].
#include<stdio.h> void main() { int arr_list[] = {10, 8, 6, 4, 2, 1}; int *ptr; for(ptr=arr_list+5;ptr>=arr_list;ptr--) { printf("%d\t", arr_list[ptr-arr_list]); } }
Output:
$ cc array-traversal.c $ ./a.out 1 2 4 6 8 10
Accessing array elements using pointer variable,
void main() { int arr_list[] = {10, 8, 6, 4, 2, 1}; int *ptr; for(ptr=&arr_list[5];ptr>=arr_list;ptr--) { printf("%d\t", *ptr); } }
Output:
$ cc array-traversal.c $ ./a.out 1 2 4 6 8 10
Another way of accessing array elements in reverse order using pointers,
#include<stdio.h> void main() { int arr_list[] = {10, 8, 6, 4, 2, 1}; int i, *ptr; for(ptr=arr_list+5,i=0;i<=5;i++) { printf("%d\t", ptr[-i]); } }
Output:
$ cc array-traversal.c $ ./a.out 1 2 4 6 8 10
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page