Hello
This piece of code works. But earlier, I had tried using (res->data[i][j]) in place of p[i][j (in line 40, in the for loop inside main()). And the program used to fail due to an access violation error.
Then I declared the variable **p within main() and assigned res->data to it. And it worked. Can anyone tell me why using res->data[i][j] didnt work. If u can, please do.
Thank you!
This piece of code works. But earlier, I had tried using (res->data[i][j]) in place of p[i][j (in line 40, in the for loop inside main()). And the program used to fail due to an access violation error.
Then I declared the variable **p within main() and assigned res->data to it. And it worked. Can anyone tell me why using res->data[i][j] didnt work. If u can, please do.
Code:
#include<stdio.h> //compiled using gcc 3.4.5 struct sam { int **data; }; struct sam* func() { int rows=2, columns=2, i, j; struct sam r; r.data=(int **)malloc(sizeof(int*)*rows); for(i=0; i<rows; i++) { r.data[i]=(int*)malloc(sizeof(int)*columns); } for(i=0; i<rows; i++) for(j=0; j<columns; j++) { r.data[i][j]=i+j; } for(i=0; i<rows; i++) for(j=0; j<columns; j++) { printf("%d", r.data[i][j]); } return &r; } main() { int i, j, rows=2, columns=2, **p; struct sam *res; res=func(); p=res->data; printf("\nIn caller"); for(i=0; i<rows; i++) for(j=0; j<columns; j++) { printf("%d", p[i][j]); } }
Comment