Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to pointer, I am lost

Tags:

c

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?

like image 616
Bing Du Avatar asked Dec 19 '22 03:12

Bing Du


2 Answers

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));
like image 120
Pradhan Avatar answered Jan 07 '23 07:01

Pradhan


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));
like image 34
Sourav Kanta Avatar answered Jan 07 '23 08:01

Sourav Kanta