【发布时间】:2014-08-14 05:47:30
【问题描述】:
嗨,我试图使用单指针传递二维整数数组。我知道我必须 传递给函数之前的类型转换数组
谁能解释为什么我们需要在传递我的代码之前进行类型转换如下?
#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); // here why i need to typecast and pass?
return 0;
}
【问题讨论】:
-
编译器怎么做?
arr不是指向 int 的指针。 -
int(*)[3]和int *是不兼容的类型 -
@AlterMann 函数期望用
int*解析二维数组的本质是错误的,因为它打算进行数组展平,它是may potentially lead to UB。