代码结构
main.c
#include <stdio.h>
#include <stdlib.h>#define LEN 100int main()
{//通过指针引用多维数组# if 1//定义多维数组int a[3][5] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};int row = sizeof(a) /sizeof(a[0]);int colum = sizeof(a[0]) / sizeof(a[0][0]);printf("row = %d, colum = %d\n", row, colum);//定义函数打印二维数组extern void PrintTwoDimArr(void* arr, int row, int colum);PrintTwoDimArr(a, row, colum);printf("修改后的二维数组为:\n");//改变二维数组中的元素值extern void ChangeValTwoDimArr(void* arr, int row, int colum);ChangeValTwoDimArr(a, row, colum);PrintTwoDimArr(a, row, colum);#endifreturn 0;
}
test1.c
#include <stdio.h>
#include <stdlib.h>
//定义函数打印二维数组
/* * 这里的技巧是,* 这个指针的类型不太好定义,因此这里将指针的类型定义为void** 然后在背调函数中将指针转换为需要的类型,然后进行操作。*/
extern void PrintTwoDimArr(void* arr, int row, int colum)
{//printf("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);int (*p)[colum] = arr;for(int i = 0; i < row; i++){//printf("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);for(int j = 0; j < colum; j++){//printf("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);//printf("%d\t", p[i][j]);printf("%d\t", *(*(p + i) + j));}printf("\n");}
}//改变二维数组中的元素值
extern void ChangeValTwoDimArr(void* arr, int row, int colum)
{int (*p)[colum] = arr;for(int i = 0; i < row; i++){for(int j = 0; j < colum; j++){p[i][j] = -p[i][j];}}
}
Makefile
main:main.c test1.cgcc -o $@ $^#./$@
clean:rm main