C:将任意大小的数组传递给函数

标签 c multidimensional-array

我正在尝试编写一个 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).

  1. 上述声明有什么问题?
  2. 应如何将数组定义为多维?

最佳答案

抛开 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/

相关文章:

C 字符串解析

c - 我找不到为什么我的程序总是说太低

c - 查找多个整数之间的最小值和最大值

java - 生成具有随机行长度的随机二维数组

javascript - 计算javascript中列的索引

c - 处理结构体指针数组的动态增长

C、if 语句和 strcmp

java - Java 中二维数组创建的维度似乎是倒退的

python - 在 numpy 中转置 4 维数组

objective-c - 对包含包含数组的对象的 Objective-c 数组进行排序