简体   繁体   中英

passing 2d array in c using pointer to pointer by typecasting

How to pass a 2D array as a parameter in C?

I was searching to pass a 2d array to a function in c and I came across the above site. I understood the first and second way of passing 2d array, but I got confused in the 3rd method, specifically, how is it even working that way?`

3) Using an array of pointers or double pointer
In this method also, we must typecast the 2D array when passing to function.
    #include <stdio.h>
    // Same as "void print(int **arr, int m, int n)"
    void print(int *arr[], int m, int n)
    {
        int i, j;
        for (i = 0; i < m; i++)
          for (j = 0; j < n; j++)
            printf("%d ", *((arr+i*n) + j));
    }

    int main()
    {
        int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int m = 3;
        int n = 3;
        print((int **)arr, m, n);
        return 0;
    }
    Output:

    1 2 3 4 5 6 7 8 9

`

The above code works fine on codeblocks. When calling print() from main(), we pass arr as argument by typecasting it to pointer to pointer , but in the function print() it dereferences only once to print the values. printf("%d ", *((arr+i*n) + j)); Shouldn't it be *((*arr+i*n) + j)); , I tried compiling this statement , it compiles but doesn't execute.

2) Using a single pointer
In this method, we must typecast the 2D array when passing to function.

#include <stdio.h>
void print(int *arr, int m, int n)
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", *((arr+i*n) + j));
}

int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print((int *)arr, m, n);
    return 0;
}
Output:

1 2 3 4 5 6 7 8 9

`

The 2nd method and the 3rd method only differ in the type of argument passed in the print() function while rest of the code is same. So what is actually the difference between the working of the functions?

easiest way to pass 2D array,

function

void PrintArray(unsigned char mat[][4]){
    int i, j;
    printf("\n");
    for(i = 0;i<4;i++){
        for(j = 0;j<4;j++)
                printf("%3x",mat[i][j]);

        printf("\n");
    }
    printf("\n");
}

main

int main(){

int i,j;
//static int c=175;
unsigned char  state[4][4], key[4][4], expandedKey[176];


printf("enter the value to be decrypted");
for(i=0;i<4;i++)
    for(j=0;j<4;j++)
        scanf("%x",(unsigned int *)&state[j][i]);
PrintArray(state);

return 0;
}

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