Can any one explain this?
#include<stdio.h>
void FunPrinter(int *x)
{
int i, j;
for(i = 0; i < 4; i++, printf("\n"))
for(j = 0; j < 5; j++)
printf("%d\t",*x++);
}
int main()
{
int x[][5] = {
{17, 5, 87, 16, 99},
{65, 74, 58, 36, 6},
{30, 41, 50, 3, 54},
{40, 63, 65, 43, 4}
};
int i, j;
int **xptr = x;
printf("Addr:%ld,Val:%ld,ValR:%ld",(long int)x,(long int)*x,(long int)**x);
printf("\nInto Function\n");
FunPrinter(&x[0][0]);
printf("\nOut Function\n");
for(i = 0; i < 4; i++, printf("\n"))
for(j = 0; j < 5; j++)
printf("%d\t",**xptr++);
return 0;
}
Output:
Addr:140734386077088,Val:140734386077088,ValR:17
Into Function
17 5 87 16 99
65 74 58 36 6
30 41 50 3 54
40 63 65 43 4
Out Function
Segmentation fault (core dumped)
Why Direct Addressing is not working? I am accessing through pointers. I have used double pointer but it’s not working.
I have also tried to use single pointer as xptr. But still not working.
You are getting a segmentation fault, because you are iterating over the wrong pointer (over the outermost dimension pointer). There are only 4 valid blocks on that dimension you can iterate over (not 20).
Here,
xand*x(use%pto print pointers, not casting) are the same value, because they both point to the beginning of the array (same address), but the pointer arithmetic’s are different (the size of element is different). You can iterate viaxpossibly needing to cast it toint *.Also, the approach you are using in the
FunPrinter– degrading a 2D array into 1D array is not guaranteed to work, it does indeed involve undefined behavior (although most reasonable compilers will compile this just fine).