【问题标题】:passing 2d array in c using pointer to pointer by typecasting通过类型转换使用指向指针的指针在c中传递二维数组
【发布时间】:2015-04-17 09:11:53
【问题描述】:

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

我正在搜索将二维数组传递给 c 中的函数,我遇到了上述站点。我理解传递二维数组的第一种和第二种方式,但我得到了 对第三种方法感到困惑,具体来说,它是如何工作的?`

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()函数中传递的参数类型不同,其余代码相同。那么这些函数的工作方式实际上有什么区别呢?

【问题讨论】:

  • 这两个示例都非常不正确,因为它们将对象解释为不同的不兼容对象。这会导致未定义的行为。没有必要推理他们做了什么,而是找到一个正确的例子。
  • @2501 但是为什么他们给出正确的输出呢?当您说“对象作为不同的不兼容对象”时,您是什么意思?
  • Geeks-for-Geeks 文章末尾的C FAQ reference 说(在末尾):最后,我们可能会明确指出,如果我们将多维数组传递给函数 [ ...] 我们不能将该函数声明为接受一个指向指针的指针。文章中的cmets也指出第3种方法是错误的。
  • 变量int arr[][3] 实际上占据了一个连续的内存区域,arr 指向它的开头。这就是单次取消引用有效的原因。就好像你的二维数组是一维的,就像你在{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} 中写的一样
  • 显然,因为它实际上并没有使用它的参数作为它需要的指针数组。更准确地说,它不会尝试取消引用数组中的“指针”,它只是显示它们。使用 %d 格式说明符。简而言之,在这个架构上,一大堆错误最终变成了正确的。它可能在 64 位非 ILP64 平台上失败。

标签: c arrays pointers multidimensional-array


【解决方案1】:

传递二维数组的最简单方法,

功能

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2018-01-04
    • 2014-01-26
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多