1

Can you explain to me why does the first element ot the 2 dimentional array is 1 in this code?

#include <stdio.h>
#include <stdlib.h>
   int main(void) {
       int i,j;
       int **p = (int **)malloc(2 * sizeof(int *));
       p[0] = (int *)malloc(2 * sizeof(int));
       p[1] = p[0];
       for(i = 0; i < 2; i++)
               for(j = 0; j < 2; j++){
                   printf("i=%d & j=%d\t",i,j);
                   p[i][j] = i + j;
                   printf("p[%d][%d]=%d\n",i,j,p[i][j]);
                   printf("this is the result of the first element %d\n",p[0][0]);
               }


       printf("this is the result %d\n",p[0][0]);
       return 0;
   }

The result is :

i=0 & j=0 p[0][0]=0

this is the result of the first element 0

i=0 & j=1 p[0][1]=1

this is the result of the first element 0

i=1 & j=0 p[1][0]=1

this is the result of the first element 1

i=1 & j=1 p[1][1]=2

this is the result of the first element 1

this is the result 1

Press to close this window...

Community
  • 1
  • 1
kyrpav
  • 756
  • 1
  • 13
  • 43

2 Answers2

3

Because the two rows p[0] and p[1] are indeed the same.

p is an array of two pointers:

int **p = (int **)malloc(2 * sizeof(int *));

The first one points to an array of size 2:

p[0] = (int *)malloc(2 * sizeof(int));

The second one points to the same array:

p[1] = p[0];

So any modification to p[1][0] will reflect on p[0][0], since both refer to the same location in memory. As you can verify, you assigned 1 to p[1][0], so p[0][0] becomes 1 too.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
  • So p[1] = p[0]; this was the mistake it sould be a new malloc to get a 2 dimentional array i suppose – kyrpav Feb 23 '15 at 23:07
1

I tried to explain in the figure ( sorry for that but its easier ).enter image description here

So to correct your mistake and to declare a proper 2-D matrix , in place of malloc for p[0] write for(int i=0; i < 2;i++)p[i] = (int *)malloc(2*sizeof(int));.

advocateofnone
  • 2,527
  • 3
  • 17
  • 39