Array Manipulation using Pointers in C
How to create array using dynamic memory allocation ?
int *arr; // declared a pointer to integer printf("\n How many elements to create:- "); scanf("%d",&size); // suppose user enters size=10 arr=(int *)malloc(size*sizeof(int));// allocating memory for 10 integers
How to accept elements in an array ?
for(i=0;i<size;i++) // accepting 10 integers scanf("%d",arr+i); // storing in 10 consecutive locations
How to display array using pointers ?
To access any location in array we use value at (*) operator in c. By using this operator we can access the value stored at that location.
printf("\n Elements of array are: ");
for(i=0;i<size;i++)
printf(" %d ",*(arr+i)); // displaying the values of 10 consecutive locations
Note: Remember the name of the array contains the base address / starting address of the array. So we can use this address to access the members in an array. So this means we can also use the normal array like explained above.