How to pass a 2D array to a function using single pointer [closed]

风流意气都作罢 提交于 2021-01-29 06:21:48

问题


I want to pass a 2D array to a function . I must receive the 2D array using a single pointer in the formal argument.


回答1:


In C when you have a 2D array, you have an array of 1D arrays. On access, an array is converted to a pointer to its first element. C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3) For an array of arrays it is a pointer to the first array. So your pointer is a pointer-to-array of type[DIM] (where DIM is the dimension of the array.

For example if you have an array of integers, e.g. int arr[3][5];, then on access you have a pointer-to-array of int[5]. The formal type is int (*)[5].

Example:

#include <stdio.h>

#define COLS 5

/* print the contents of a 2d array */
void prn2d (int (*a)[COLS], int rows)
{
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < COLS; j++)
            printf (" %2d", a[i][j]);
        putchar ('\n');
    }
}

int main (void) {
    
    int arr[][COLS] = { {1, 2, 3, 4, 5},
                        {6, 7, 8, 9, 10},
                        {11, 12, 13, 14, 15} },
        n = sizeof arr/sizeof *arr;
    
    prn2d (arr, n);     /* pass arr to your function */
}

Example Use/Output

$ ./bin/pass2darr
  1  2  3  4  5
  6  7  8  9 10
 11 12 13 14 15



回答2:


#include <stdio.h>

void func(char* str_arr, int m, int n)
{
        for (int i = 0; i < m; i++) {
                printf("%s ", str_arr + n * i);
        }

        printf("\n");
}

int main()
{
        char str_arr[5][7] = {"But,", "what", "is", "the", "point?"};

        func((char*) str_arr, 5, 7);

        return 0;
}

OUTPUT

But, what is the point?

And the output is my question (- -)




回答3:


regarding:

printf("%s ", str_arr + sizeof(char) * n * i);

slightly rewritten:

printf("%s ", &str_arr[n * i];

shows that the code is stepping through the memory occupied by the array str_arr[][] and the 'output conversion' specifier %s is saying to output the string, starting at str_arr[0] and treating the whole array as a single contiguous set of bytes. where the second iteration of the loop accesses str_arr[7] and the third iteration of the loop accesses str_arr[14] etc.



来源:https://stackoverflow.com/questions/62495423/how-to-pass-a-2d-array-to-a-function-using-single-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!