Указатель на многомерный массив - PullRequest
2 голосов
/ 07 апреля 2020
/* Demonstrates passing a pointer to a multidimensional */
/* array to a function. */

#include <stdio.h>

void printarray_1(int (*ptr)[4]);
void printarray_2(int (*ptr)[4], int n);

int main(void)
{
    int multi[3][4] = { {1, 2, 3, 4},
                        {5, 6, 7, 8},
                        {9, 10, 11, 12} };

    // ptr is a pointer to an array of 4 ints.
    int (*ptr)[4], count;

    // Set ptr to point to the first element of multi.
    ptr = multi;

    // With each loop, ptr is incremented tto point to the next
    // element (that is, the next 4-elements integer array) of multi.

    for (count = 0; count < 3; count++)
        printarray_1(ptr++);

    puts("\n\nPress Enter...");
    getchar();
    printarray_2(multi, 3);
    printf("\n");

    return 0;
}

void printarray_1(int (*ptr)[4])
{
    // Prints the elements of a single 4-element integer array.
    // p is a pointer to type int. You must use a typecast
    // to make p equal to the address in ptr.

    int *p, count;
    p = (int *)ptr;

    for (count = 0; count < 4; count++)
        printf("\n%d", *p++);
}

void printarray_2(int (*ptr)[4], int n)
{
    // Prints the elements of an n by 4-element integer arrray.

    int *p, count;
    p = (int *)ptr;

    for (count = 0; count < 4; count++)
        printf("\n%d", *p++);
}

В определении функций printarray_1 & 2 указатель int p назначается (int *) ptr. Почему?

В объявлении указателя главной функции скобка ставит * ptr в более высокий приоритет, чем [4]. но (int *) ptr не имеет смысла для меня. Не могли бы вы объяснить, почему?

Ответы [ 2 ]

2 голосов
/ 07 апреля 2020

Синтаксически и семантически правильный способ получения p из ptr:

    p = *ptr;

... при попытке извлечь массив int p[4] (объявлен как int *p) из указателя на массив int(*ptr)[4]. Это исключает необходимость любого литья.

0 голосов
/ 07 апреля 2020

(int *) p это так же, как int * p
Я советую вам сделать простую программу и попробовать ее

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...