i am trying to create a 2d array using double pointer…
my code is…
int **p1;
p1=(int **) malloc(2*sizeof(int *));
for(int i=0;i<2;i++)
{
p1[i]=(int *) malloc(3*sizeof(int));
for(int j=0;j<3;j++)
{
scanf("%d",(p1+i)+j);
}
}
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
printf("%d\n",*(*(p1+i)+j));
}
}
as i have declared a double pointer (**p1) for it and i am able to put data at all those places using my scan scanf("%d",(p1+i)+j); statement. And to dereference i can use print statement as i have done printf("%d\n",*(*(p1+i)+j));
but why it is breaking during print statement but accepting my scan statement.
but why this is giving me correct response…
int mybox[][4]={{1,2,3,4},{5,6,7,8}};//we have to provide subscript;
for(int i=0;i<2;i++){
for(int j=0;j<4;j++){
printf("%d",mybox[i][j]);//will print all elements
}
}
printf("%d",*(*(mybox)+1));//give me 2
printf("%d",*(*(mybox+1)+1));//give me 6
printf("%d",*(*(mybox+1)+3));//give me 8
Your
scanfportion is implemented incorrectly. It destroys your data. Ironically, the problem does not reveal itself duringscanfphase, but instead causes a crash atprintfstage.The correct
scanfcode might look as followsNote the extra
*. What you really need here isYou can write it this way if you want. But you can notice that the outer
&“annihilates” with the next nested*, so the above is equivalent toHowever, my advice to you is to stop using the barely-readable
*-and-+combination for array element access and start using the[]instead. This is how your code should have looked from the very beginningOn top of that, since this is taggged C, avoid using
sizeofwith types as much as possible and stop casting the result ofmalloc. A better variant would be