简体   繁体   English

通过类型转换使用指向指针的指针在c中传递2d数组

[英]passing 2d array in c using pointer to pointer by typecasting

How to pass a 2D array as a parameter in C? 如何在C中将2D数组作为参数传递?

I was searching to pass a 2d array to a function in c and I came across the above site. 我正在搜索将2d数组传递给c中的函数,而我遇到了上述站点。 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?` 我理解了传递2d数组的第一种和第二种方法,但是我对第3种方法感到困惑,特别是,它甚至如何以这种方式工作?

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. 当从main()调用print()时 ,我们将arr作为参数传递,将其类型转换为指针的指针,但是在函数print()中,它仅取消引用一次以打印值。 printf("%d ", *((arr+i*n) + j)); Shouldn't it be *((*arr+i*n) + j)); 应该不是*((*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. 第二种方法和第三种方法仅在print()函数中传递的参数类型不同,而其余代码相同。 So what is actually the difference between the working of the functions? 那么功能的工作实际上有什么区别?

easiest way to pass 2D array, 通过2D数组的最简单方法

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;
}

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

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