版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kwansy/article/details/79827826
如果需要给函数传递一个二维数组,又不想在函数原型中给出第二维的长度,则可以考虑把数组直接传进去,形参用void *
接收。在函数内可以把形参指针转换成其他类型。
下面给出一个例子,函数func接收一个二维数组,在函数内转换成一维数组进行逆序处理。
#include <stdio.h>
#include <malloc.h>
#define ROW 4
#define COL 4
void func(void *a)
{
int *arr = (int *)a;
int temp;
for (int i = 0; i < ROW * COL / 2; i++)
{
temp = arr[i];
arr[i] = arr[ROW * COL - 1 - i];
arr[ROW * COL - 1 - i] = temp;
}
}
int main()
{
int arr[ROW][COL] =
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }
};
func(arr);
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
printf("%4d", arr[i][j]);
}
putchar('\n');
}
}