4

This is my code, it compile and runs:

#include <stdio.h> 
#include <stdlib.h>

int main() 
{ 
    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++) 
            {
                p[i][j] = i + j; 
            }
    } 

    printf("p[0][0] = %d",p[0][0]); 

    return 0; 
}

When this program is run, I got: P[0][0] = 1. Why not P[0][0] = 0?

Noam M
  • 3,156
  • 5
  • 26
  • 41
Bing Du
  • 61
  • 2

2 Answers2

7

You are making p[0] and p[1] point to the same memory location. Later on, you run this loop:

for(i = 0; i < 2; i++) 
            for(j = 0; j < 2; j++) 
                    p[i][j] = i + j;

which sets p[0][0] to 0. However, it is followed by setting p[1][0] to 1. Since p[0] and p[1] are equal, p[0][0] ends up being 1 finally.

What you likely intended instead of

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

was a separate malloc for p[1] as well. Like this:

p[0] = malloc(2 * sizeof(int)); 
p[1] = malloc(2 * sizeof(int));
Gopi
  • 19,784
  • 4
  • 24
  • 36
Pradhan
  • 16,391
  • 3
  • 44
  • 59
4

P[1] and p[0] are being assigned to the same memory location. So any change in p[1] changes p[0].You should allocate separate space for p[1] .

p[1]=malloc(2 * sizeof(int));
Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29