#include <stdio.h>
int main()
{
char str[3][15] = {"Pointer to","char","program"};
char (*pt)[15] = str; // statement A
char *p = (char *)str; // statement B
printf("%s\n",p[3]); // statement C - Seg Fault in this line
printf("%s\n",p); // working properly displaying "Pointer to"
printf("%s\n",p+1); // here it is pointing to second element of first array so displaying "ointer to"
printf("%s\n",pt+1); // printing properly "char" as expected
int num[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
int (*nm)[3] = num[1];
int *n = num;
printf("n - %d\n",n[10]); // statement D
printf("nm - %d\n",nm[0][0]);
return 0;
}
My questions:
Please help me to get clear idea about the data storing mechanism in case of char array and int array
In above program I am understanding that when pointer to char array is pointed to 2D array of char as shown in statement A it is displaying properly but when it is pointed by normal char pointer and trying to print the char in statement C it is getting SegFault, instead it should print 'n'(3rd number char in first array "Pointer to") so having confusion why in case int array i am getting proper element n = 11 in statement D and why in this case (statement C) it is not properly printing.
How the data will be stored in case of char array will it be stored in this form shown below
char str[3][15] = {{'P','o','i','n','t','e','r',' ','t','o'},
{'c','h','a','r'},
{'p','r','o','g','r','a','m'}};
if it is stored like this then it should work like array of integer pointer shown in statement D Please help me to guide about this issue and clarify the issue I have in case of char and int array storage.