简体   繁体   中英

Point an array of pointers to an array of arrays

I am trying to point to an array of arrays (learning purposes). I use this line for that purpose:

int Arr[6][6];    
int (*ptr)[6][6];
ptr = &Arr;

Is this correct? (EDIT: I intend to use a pointer to a 6x6 array. Also, considering I wish to take input and print it out also, which kind of declaration is better? array of pointers or pointer to 6x6 array?)

Next,

(The "reading and printing of 2d array using pointer" code is a total mess, which is why I won't show it here.)

I want to use scanf and printf to take input through ptr (which should assign it to Arr), and then print both Arr and ptr to see the syntax (and if it works at all). Obviously both printed arrays should be the same.

What syntax should I use? It's extremely confusing and I hope this will help me learn better.

Reading and printing through pointer:

for (i = 0; i < 6; i++)

{
    printf_s("\nEnter values for row %d (Enter 0 for 1-1, 2-2 etc.:\n", i + 1);
    for (j = 0; j < 6; j++)
    {
        printf_s("Row %d Column %d", i + 1, j + 1);
        scanf_s("%d", &(*ptr)[i][j]); ........(ptr)[i][j] doesn't allocate to Arr correctly
    }
}
for (i = 0; i < 6; i++)
    {
        printf_s("\n");
        for (j = 0; j < 6; j++)
        {
            printf_s("%d\t", (*ptr)[i][j]); .........*(ptr)[i][j] is wrong because it dereferences the whole 2D array.
        }
    }

Credits: haccks (I changed the question a lot of times, so I'm pointing out mistakes I did during the same)

int (*ptr)[6][6]; declare ptr as a pointer to an array of 6 elements , each of which are array of 6 integers ( of type int (*)[6][6] ) . Now &Arr is also int (*)[6][6] type, your assignment is legal.
In your scanf_s argument, you are missing & . This should be

scanf_s("%d", &(*ptr)[i][j]);  

Note that (*ptr)[i][j] is of int type. It is like Arr[i][j] . To store values to Arr[i][j] you need & , similarly & is used here to store values (*ptr)[i][j] .

See the corrected program :

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

int main(void)
{
    int Arr[6][6];
    int (*ptr)[6][6];
    ptr = &Arr;

    for (int i = 0; i < 6; i++)
    {
        printf("\nEnter values for row %d (Enter 0 for 1-1, 2-2 etc.:\n", i + 1);
        for (int j = 0; j < 6; j++)
        {
            printf("Row %d Column %d: ", i + 1, j + 1);
            scanf("%d", &(*ptr)[i][j]);

        }
    }
    for (int i = 0; i < 6; i++)
    {
        for (int j = 0; j < 6; j++)
            printf("%d\t", (*ptr)[i][j]);
        printf("\n");
    }

}    

Output: http://ideone.com/q6BQ61

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