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