The need:
This is a simple program to show that pointer is equivalent to a one dimensional array of same datatype and how a pointer variable can be used as an array.
This is a simple program to show that pointer is equivalent to a one dimensional array of same datatype and how a pointer variable can be used as an array.
--------------------------------------------
#include<stdio.h> #include<stdlib.h> #define max 5 main() { int i; int *p,*q; p=(int *)malloc(max * sizeof(int)); q=p; printf("Enter %d integers\n",max); for(i=0;i<max;i++) { printf("Enter number %d =>\t",i); scanf("%d",p++); } printf("\nyou entered\n"); for(i=0,p=q;i<max;i++) { printf("%d whose address is %d\n",*p,p); p++; } return 0; }--------------------------------------------
The approach:
This program takes 5 integers from user, store them in memory and prints back for user. This is a trivial task. Here I have shown how a pointer variable (in our case p) can be used as an array of integers. This can be done for other data-types and even with derrived datatypes. First of all the pointer p is initialised and allocated sufficient memory (here using malloc function). After that five integers are scanned one by one and each time pointer p is incremented. In each increment p is automatically set to point to the next integer location in the memory. The initial value of p (starting location of array) is temporarily stored in other variable q. Which is later used to access the array to print it.
No comments:
Post a Comment
feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply