简体   繁体   中英

how to access array elements using double pointer in c

It puts on the screen the last 2 numbers and other 2 strange numbers. How can I print all elements? I tried to keep the beginning of the double pointer **fool in another pointer **st. But it seems it doesn't work.

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

typedef struct a {
    int x;

}A_t;

typedef struct b {

    A_t **y;

}B_t;

int main() {


    int i, j;

    A_t **fool, **st;

    fool = (A_t**)malloc(2 * sizeof(A_t*));
    st = fool;

    for(i = 0; i < 2; i++) {

        fool[i] = (A_t*)malloc(2 * sizeof(A_t));

        for(j = 0; j < 2; j++) {
            printf("NR: ");
            scanf("%d", &(*fool)[j].x);
        }

    }

    fool = st;
    for(i = 0; i < 2; i++) {
        for(j = 0; j < 2; j++) {
            printf("%d ", (*fool + i)[j].x);
        }
    }

    return 0;
}

它应该是&fool[i][j].xscanffool[i][j].xprintf

It's because you're not reading into the second "row" of fool . scanf("%d", &(*fool)[j].x); dereferences fool , which you can model as fool[0] , then accesses the j-th element (so fool[0][j] . Of course, because you never change the first index, the last two values read will occupy fool[0][0] and fool[0][1] . You're then getting random values for the other two simply because reading an uninitialized variable is an undefined operation. In reality, you tend to get whatever was residing in that area of memory before your application.

Instead, you can either use the syntax you have used in printf (eg scanf("%d", &(*fool+i)[j].x) ), or, as KerrekSB has just posted above while I was typing this, use the standard array access operations instead.

To elaborate on that, fool[i][j] is equivalent to (*fool+i)[j] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM