C Different method of passing matrix of pointers to function

╄→гoц情女王★ 提交于 2020-02-03 09:21:24

问题


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?


回答1:


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).

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
}

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

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

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.

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.




回答2:


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

You cannot omit the second dimension of the array.

So you need to have your prototype like this:

void performCmd(int *cmd[][maxArgSize]);

and call the method like this:

performCmd(cmd);



回答3:


You would probably have to pass a char double pointer, and the two dimensions as other parameters.

void performCmd(char** cmd, int maxCmdSize, int maxArgSize) {
  //do whatever this function does
}


来源:https://stackoverflow.com/questions/59011624/c-different-method-of-passing-matrix-of-pointers-to-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!