Dymov
Dymov

Reputation: 1

pointer to pointer got strange output

I wrote a sample program to test pointers. But I get confused with the output. The code looks like this

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

int main(void){
    int **array;
    int *num;
    array=malloc(sizeof(int *)*10);
    int i;

    for(i=0;i<10;i++){
        num=&i;
        printf("&i=%d num=%d\n",&i,num);
        array[i]=num;
    }


    for(i=0;i<10;i++){
        printf("array[%d]=%d *(array[%d])=%d\n",i,array[i],i,*(array[i]));
    }
    return 0;
}

I expect the output of *(array[i]) to be 9 for each i. But I got numbers from 0 to 9. I can't find out why. Anybody can help ? Thanks!

Upvotes: 0

Views: 28

Answers (1)

Chris Loonam
Chris Loonam

Reputation: 5745

The behavior deviates from what you expect because you use i as the index in the second loop. As you go through the second loop, i goes from 0-9 again. So, since each entry in array points to i, 0-9 is printed.

If you did this instead

int j;
for (j = 0; j < 10; j++) {
    printf("array[%d]=%d *(array[%d])=%d\n", j, array[j], j, *(array[j]));
}

You'll get your expected output (which will be 10, not 9, since the loop breaks once i hits 10).

Upvotes: 1

Related Questions