簡體   English   中英

通過類型轉換使用指向指針的指針在c中傳遞2d數組

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

如何在C中將2D數組作為參數傳遞?

我正在搜索將2d數組傳遞給c中的函數,而我遇到了上述站點。 我理解了傳遞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

`

上面的代碼在代碼塊上工作正常。 當從main()調用print()時 ,我們將arr作為參數傳遞,將其類型轉換為指針的指針,但是在函數print()中,它僅取消引用一次以打印值。 printf("%d ", *((arr+i*n) + j)); 應該不是*((*arr+i*n) + j)); ,我嘗試編譯此語句,它可以編譯但無法執行。

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

`

第二種方法和第三種方法僅在print()函數中傳遞的參數類型不同,而其余代碼相同。 那么功能的工作實際上有什么區別?

通過2D數組的最簡單方法

功能

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

主要

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