C将指针矩阵传递给函数的不同方法 [英] C Different method of passing matrix of pointers to function

查看:58
本文介绍了C将指针矩阵传递给函数的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将此二维指针数组传递给函数:

I want to pass this two dimensional array of pointers to a function:

array:

*cmd[maxCmdSize][maxArgSize]

function:

void performCmd(char *cmd[maxCmdSize][maxArgSize])

如何在不声明函数尺寸大小的情况下实现这一目标?

How to achieve this without declaring the size of the dimensions in the function?

推荐答案

使用VLA参数(VLA,即可变长度数组是C11的可选标准扩展名),您可以
传递大小作为另一个参数(必须在VLA之前)。

With VLA parameters (VLAs, i.e., variadic-length arrays, are an optional standard extension of C11), you can pass the size as another parameter (which needs to preceede the VLA).

最里面的索引,在该索引处数组衰减为指针( int * cmd [] [函数参数中的maxArgSize] 等效于 int *((* cmd)[maxArgSize] ),无需传递且不会影响多维数组-

The innermost index, where the array decays to a pointer (an int *cmd[][maxArgSize] in a function parameter is equivalent to int *(*cmd)[maxArgSize]) need not be passed an does not affect multidimensional array-based pointer arithmetic.

int performCmd(int maxArgSize, char *cmd[][maxArgSize]);
int performCmd(int maxArgSize, char *cmd[][*]); //compatible alternative declaration


int performCmd(int maxArgSize, char *cmd[][maxArgSize])
{
    return &cmd[1][0]-&cmd[0][0]; //returns maxArgSize
}

在声明(但未定义)中,VLA size可以用 * 代替。

Also in a declaration (but not definition), the VLA size can be replaced with *.

(然后在定义中,size也可以是任何非常量表达式(

(In the definition then, the size can also be any nonconst expression (including possibly a function call) not necessarily just a simple variable reference.)

没有VLA支持,您可以简单地将指针传递给基本类型和尺寸,然后使用

Without VLA support you can simply pass a pointer to the base type and the dimensions, and then use that to emulate multidimensional pointer arithmetic on the base array.

给出,例如 char x [2] [3] [4] [5] ; & x [1] 表示(char(*)[3] [4] [5]) x + 1 ,(即(char *)x + 1 *(3 * 4 * 5)), & x [1] [1] 表示(char(*)[4] [5])((char(*)[3] [4] [5] )x + 1)+ 1 (即(char *)x + 1 *(3 * 4 * 5)+ 1 *(4 * 5)),等等。当数组维是动态的时,它的工作原理是相同的,然后您可以使用此数学运算来翻译动态维,基本指针和一组ind无需依靠VLA支持即可解决问题。

Given, for example char x[2][3][4][5];, &x[1] means (char(*)[3][4][5])x + 1, (i.e., (char*)x+1*(3*4*5)), &x[1][1] means (char (*)[4][5])((char(*)[3][4][5])x+1) + 1 (i.e., (char*)x+1*(3*4*5)+1*(4*5)), etc. This works the same when the array dimensions are dynamic, and then you can use this math to translate a dynamic dimension, a base pointer, and a set of indices into an offset without having to rely on VLA support.

这篇关于C将指针矩阵传递给函数的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆