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?
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));
                        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));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With