简体   繁体   English

如何在C中使用双指针访问数组元素

[英]how to access array elements using double pointer in c

It puts on the screen the last 2 numbers and other 2 strange numbers. 它在屏幕上显示最后2个数字和其他2个奇数。 How can I print all elements? 如何打印所有元素? I tried to keep the beginning of the double pointer **fool in another pointer **st. 我试图将双指针** fool的开头保留在另一个指针** 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 . 这是因为您没有读到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. 解引用fool ,您可以将其建模为fool[0] ,然后访问第j个元素(因此fool[0][j] 。当然,由于您从不更改第一个索引,因此读取的最后两个值将占据fool[0][0]fool[0][1] ,您将获得其他两个的随机值,这仅仅是因为读取未初始化的变量是未定义的操作。实际上,您倾向于获得位于该区域的任何内容。在应用程序之前存储。

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. 相反,您可以使用在printf使用的语法(例如scanf("%d", &(*fool+i)[j].x) ),也可以使用KerrekSB刚刚在上面键入此内容时发布的语法。 ,请改用标准数组访问操作。

To elaborate on that, fool[i][j] is equivalent to (*fool+i)[j] . 对此, fool[i][j]等效于(*fool+i)[j]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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