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...

2
  • You intended p[0] and p[1] to refer to the same singular row? Commented Feb 23, 2015 at 23:04
  • Most likely not related to your problem, but do not cast the result of malloc(). Commented Feb 23, 2015 at 23:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So p[1] = p[0]; this was the mistake it sould be a new malloc to get a 2 dimentional array i suppose
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));.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.