我正在尝试编写一个 C 程序,该程序从文本文件读取输入并将其放入二维数组中,其中行是行,列是字符。
但是读完以下文章后我很困惑:
http://c-faq.com/aryptr/pass2dary.html
我正在考虑的函数定义是
int processArray(char **text) {
...
...
}
我试图传递一个指向二维数组的指针,直到运行时我才知道其尺寸。我希望能够使用两个方括号 [] []
访问元素但是在链接中显示以下内容:
An intermediate pointer would have to be used when attempting to call it with a two-dimensional array:
extern g(int **ipp); int *ip = &array[0][0]; g(&ip); /* PROBABLY WRONG */
but this usage is misleading and almost certainly incorrect, since the array has been ``flattened'' (its shape has been lost).
- 上述声明有什么问题?
- 应如何将数组定义为多维?
最佳答案
抛开 VLA,您可以使用一个简单的指针来指向您的矩阵:
#include "stdio.h"
#define MAX_ROWS 2
#define MAX_COLS 2
void test (int *matrix, int col_max, int row_max)
{
for (int i=0; i<row_max; i++)
{
for (int j=0; j<col_max; j++)
{
printf("matrix[%d][%d]= %d\n", i, j, *(matrix+(i*col_max)+j) );
}
}
}
int main(void)
{
int matrix[MAX_ROWS][MAX_COLS] = { {1,2}, {3,4} };
test(&matrix[0][0], MAX_ROWS, MAX_COLS);
return 0;
}
关于C:将任意大小的数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43141506/