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);
}
posted @   ijpq  阅读(22)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
点击右上角即可分享
微信分享提示