In the last tutorial I told you about the memory allocation for arrays. If you are still not comfortable with that topic then I would suggest you to go through that tutorial at least once to understand this tutorial. Today I will tell you about the usage of pointers with arrays. As I said earlier pointer works faster in accessing elements of arrays then by accessing using its subscript. For convenience programmers generally adopt the subscript method but for making an efficient program it is always recommended to make use of pointers.
Note: This tutorial is all about programs, so I will give some good examples to explain the topic. Now I am assuming you are comfortable with the basic C language statements, so I will not explain about them explicitly.
Access Array Elements using Pointer
#include<stdio.h> int main( ) { int x,*y; int nums[]={4,53,44,785,124}; for(x=0;x<5;x++) { printf("naddress=%u",&nums[x]); printf(" element=%d",nums[x]); } printf("n"); y=&nums[0]; for(x=0;x<5;x++) { printf("naddress=%u",y); printf(" element=%d",*y); y++; /* Pointer is incrementing */ } return 0; }
Explanation
- First of all I have declared an integer array with name nums. The size of the array is five elements. I have also declared an integer variable x and an integer pointer y.
- After that I have used two for loops. In the first one I have printed the elements and address of each element of the array.
- Now after the first for loop I have assigned the address of first array element into an integer pointer y.
- In the second loop I am displaying the address of array elements and its values by using that integer pointer y.
- To access all the values inside an array I am incrementing the integer point continuously within loop.
Points to Remember
- Now with the above program I have again verified that array elements are always stored in contiguous memory locations.
- With the second for loop, consider carefully that an integer pointer y always points to the next element after incrementing it to 1 (this is one of the core concept of pointers in C).
- To access all the values we have used y integer pointer with printf() function.
What we have learnt?
With the program we have learnt that we can access the whole array by using pointers if we know the base address or address of first element of array.
Another way to get the base address of an array
#include<stdio.h> int main() { int x; int nums[]={4,53,44,785,124}; printf(" address of first element %u",&nums[0]); printf("n another way to get the address of first element %u",nums); return 0; }
Output
Explanation
With the above program we conclude that we can also access the base address of an array by just typing its name.