The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
In C Programming pointers and arrays are very closely related to each other in terms of functionality. Both pointers as well as arrays uses consecutive memory locations to store the data with one key difference in accessing the data. Pointer uses address to access the data stored in a memory location whereas array uses index value to access the data stored in a memory location. Fortunately data or strings initialized using the pointer variable can be accessed using array and vice versa.
#include <stdio.h> int main() { char *ptr ="pointer array", i; for(i=0; i<13; i++) printf("%c",ptr[i]); return 0; }
In the above example program *ptr is a char pointer variable which is initialized by a string then the same pointer variable is used as an array to access the value get stored by a pointer variable *ptr.
#include <stdio.h> int main() { char arr[13] = "Pointer array", i, *ptr; ptr = arr; for(i =0; i<13; i++) printf("%c",*ptr++); return 0; }
In the above example program arr[13] is a char array variable which is initialized by a set of characters then the address of first element in an array is assigned to the pointer variable which is then post incremented to print all the characters initialized to the array variable arr[13].
There are four different syntaxes are used to express the Pointer and array elements. Two syntaxes for array and two syntaxes for pointer.
#include <stdio.h> int main() { int i, a[3] = {10, 11, 12}; for(i = 0; i < 3; i++) { printf("%d \t", a[i]); printf("%d \t", i[a]); printf("%d \t", *(a + i)); printf("%d \n", *(i + a)); } return 0; }
In the above example program array can express their elements either a[i] or i[a]. If array can express their elements in two ways then pointers too can express their elements in two ways (*(a + i) or *(i + a)) as pointers and arrays are all a same family.
The general form of two dimensional array looks arr[i] [j], i represents the number of rows in an array whereas j represents the number of column in an array. The base address of an array is arr[0][0].
#include <stdio.h> int main() { int *iptr; int i, a[2][2] = {10, 11, 12, 13}; iptr = &a[0][0]; for(i = 0; i < 4; i++) { if(i == 2) { printf("\n"); } printf("%d ", *(iptr+i)); } return 0; }
In the above example program two dimensional array is declared and initialized. Though it is a two dimensional array, the elements get stored in the consecutive memory locations. Thus with pointers capability we access all the elements which we initialized to the two dimensional array earlier.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019