Table of Contents
show
An array of pointers is a collection of address. The address in an array of pointers could be the address of isolated variables or the address of array elements or any other addresses.
The only constraint is that all pointers in an array must be of same type
#include<stdio.h>
int main()
{
int a=10, b=20, c=30;
int *arr[3] = {&a,&b,&c};
printf("the values are:\n");
printf("%d\t%d\t%d\n",a,b,c);
printf("%d\t%d\t%d\n",*arr[0],*arr[1],*arr[2]);
return 0;
}
Output
the values are:
10 20 30
10 20 30
Pointers are very helpful in handling character arrays with rows of varying lengths.
Example
Example Program: Sorting of names
#include<stdio.h>
#include<string.h>
int main()
{
char name[10][8],tname[10][8],temp[8];
int i,j,n;
printf("Enter number of names");
scanf("%d",&n);
printf("\n Enter names\n");
for(i=0;i<n;i++)
{
scanf("%s",name[i]);
strcpy(tname[i],name[i]);
}
printf("\nBefore sorting\n");
for(i=0;i<n;i++)
{
printf("%s\n",tname[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(name[i],name[j]) >0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("\nAfter sorting\n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
return 0;
}
Output
C:\TDM-GCC-64>gcc 3_sorting_names_ptr.c
C:\TDM-GCC-64>a
Enter number of names3
Enter names
cab
bac
abc
Before sorting
cab
bac
abc
After sorting
abc
bac
cab
C:\TDM-GCC-64>
Pointer to Pointer
- A pointer that holds the address of another pointer variable is known as pointer to pointer
- Such a pointer is said to exhibit multiple levels of indirection
- ANSI C standard says that all compilers must handle at least 12 levels of indirection
#include<stdio.h>
int main()
{
int a=10;
int *p1 = &a;
int **p2= &p1;
int ***p3= &p2;
printf("%d\t%d\t%d\n",*p1, **p2, ***p3);
return 0;
}
Output
10 10 10
Pointer to array
A pointer can be created to point to complete array instead of pointing to the individual elements of an array of isolated variables. Such a pointer is known as pointer to an array
Example
int (*p1)[5]; // p1 is a pointer to an array of 5 integers
#include<stdio.h>
int main()
{
int arr[2][2] ={ {2,1},{3,5}};
int (*p1)[2][2]= arr;
printf("address of row 1 is %p\n", arr[0]);
printf("address of row 2 is %p\n", p1+1);
return 0;
}
Output
address of row 1 is 000000000062FE00
address of row 2 is 000000000062FE08
Views: 0