Pointer to Array of Pointers in C

C Code for pointer to array of char* ie pointer to strings.
#include<stdio.h>
int main()
{
    /*array of strings*/
char arr[3][10]={
            "Ram",/*first string ie first char array*/
            "Bhagwan",
            "Yeshu"
            };
/*pointer to array.Each array is 1-d array of chars ie each array is string*/
char (*p)[10];
p=(char *)arr;/*  p=arr+0 so p first points to first char array ie first string Ram*/

char* pp;


/*first pp holds the pointer to the first array*/
pp=p;
printf("\nbase address of first array is:%u,%u\n",pp,&arr[0][0]);
printf("and first array is:%s\n",pp);//*pp core dump
printf("and first char of first array is:%c\n",*pp);
printf("and second char of first array is:%c\n",*(pp+1));

/*  pp now points to second char array ie second string Raheem*/
pp=p+1;
printf("\nbase address of second array is:%u,%u\n",pp,&arr[1][0]);
printf("and second array is:%s\n",pp);//or *(p+1)
printf("and first char of second array is:%c\n",*pp);
printf("and second char of second array is:%c\n",*(pp+1));


/*  pp now ipoints to third char array ie third string Yeshu*/
pp=p+2;
printf("\nbase address of ithird array is:%u,%u\n",pp,&arr[2][0]);
printf("and third array is:%s\n",pp);//or *(p+2)
printf("and first char of third array is:%c\n",*pp);
printf("and second char of third array is:%c\n",*(pp+1));


printf("\nnow accessing arrays through ptr\n");
int i,j;
for(i=0;i<3;i++)
{
    pp=p+i;//p,p+1,p+2
    for(j=0;j!='\0';j++);
    {
        printf("%s ",(pp+j));//pp,pp+1,pp+2
    }
    printf("\n");
}
return 0;
}
/*
base address of first array is:3219311258,3219311258
and first array is:Ram
and first char of first array is:R
and second char of first array is:a

base address of second array is:3219311268,3219311268
and second array is:bhagwan
and first char of second array is:b
and second char of second array is:h

base address of ithird array is:3219311278,3219311278
and third array is:Yeshu
and first char of third array is:Y
and second char of third array is:e

now accessing arrays through ptr
Ram
Bhagwan
Yeshu

*/

No comments:

Post a Comment