All implementations of two-dimensional array parameter passing
IN C
gcc 5.4.1 c99
gdb 7.11.1
0X01
array bound are fully determined at compile time.
#include <stdio.h> #define R 3 #define C 4 void func(int arr[R][C]) { for (int i=0; i <R;++i){ for (int j =0; j<C;++j){ arr[i][j] = i+j; printf("%d,", arr[i][j]); } } } int main() { int arr[R][C] = {0}; func(arr); return 0; }
0x02
this is the first choice for dealing with 2darray. operating pointer to element of array and malloc with free should be considered.
#include <stdio.h> #include <stdlib.h> void func(int* array, int rows, int cols) { int i, j; for (i=0; i<rows; i++) { for (j=0; j<cols; j++) { array[i*cols+j]=i+j; printf("%d,", array[i*cols+j]); } } } int main() { int rows = 3, cols = 4; // or you can call scanf assigning value to rows and cols. int *x; /* obtain values for rows & cols */ /* allocate the array */ x = malloc(rows * cols * sizeof(*x)); /* use the array */ func(x, rows, cols); /* deallocate the array */ free(x); }
0x03
there are other methods that impl 2darray, such as only denote the second dim of array A[][N]. but those methods are less practical.
in addition, impl this methods by declaring pointer to pointer is a bit of complicated.
pointer to pointer code example as follow:
void func(int** array, int rows, int cols) { int i, j; for (i=0; i<rows; i++) { for (j=0; j<cols; j++) { array[i][j] = i*j; } } } int main() { int rows, cols, i; int **x; /* obtain values for rows & cols */ /* allocate the array */ x = malloc(rows * sizeof *x); for (i=0; i<rows; i++) { x[i] = malloc(cols * sizeof *x[i]); } /* use the array */ func(x, rows, cols); /* deallocate the array */ for (i=0; i<rows; i++) { free(x[i]); } free(x); }
本文来自博客园,作者:ijpq,转载请注明原文链接:https://www.cnblogs.com/ijpq/p/15428302.html
分类:
C/CPP
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 你所不知道的 C/C++ 宏知识
· 聊一聊 操作系统蓝屏 c0000102 的故障分析
· DeepSeek V3 两周使用总结
· 回顾我的软件开发经历(1)
· C#使用yield关键字提升迭代性能与效率
· 低成本高可用方案!Linux系统下SQL Server数据库镜像配置全流程详解
· 4. 使用sql查询excel内容