c - 如何将多维指针/数组传递给递归函数

标签 c pointers recursion multidimensional-array

我想编写一个函数,它接受一个包含“n”个元素的“m”维数组,以及一个指向其他简单函数的指针。该函数将在每个维度调用自身,迭代其元素,并在每次提到的指针指向的函数时调用(简单的)。 问题是我找不到一种方法来定义一个函数足够通用来接受任何维度的数组,或指向任何维度的数组的指针。基本上是因为每次函数调用自身时,它都会摆脱一维,这与函数原型(prototype)和定义不兼容。 我编写了一个函数,它接受一个单维指针,并根据其他两个参数(即元素总数和每个维度的大小)将其威胁为多维指针。

int main(int argc, char **argv)
{
    void goesThrough (int *, int *, size_t, void (*) (int));
    void print (int);

    int array[] = {1, 2, 3, 4, 5, 6};
    int (* ptrToArray) = array;

/*
 * Arguments are a pointer to an array, an array of sizes for each 
 * dimension, the amount of elements, and a pointer to whatever 
 * function.
 */
    goesThrough (ptrToArray, (int []) {2, 3}, 6, print);
    return 0;
}

void goesThrough (int * anArray, int * dimSize, size_t quantity,
                  void (* aFunction) (int))
{
    size_t index;

    for (index = 0; index < (* dimSize); ++index)
    {
        if (quantity / (* dimSize) > 1)
        {
            goesThrough (anArray + (index * (quantity /(*dimSize))),
                         dimSize + 1, quantity / (* dimSize), aFunction);
        }
        else
        {
            aFunction (anArray[index]);
        }
    }
}

void print (int aValue)
{
    printf ("%d ", aValue);
}

但是,我发现这种方法有两个缺点。感觉就像是 如果出现问题,编译器将无济于事;要读取/写入这些数组中的单个成员,我还需要编写自己的函数。

问题1:如何使用多维数组编写此代码?

问题2:在这种情况下,递归是比循环更好的方法吗?如果没有,我希望有一个使用循环的示例,(无论如何我都会这样做);)。为了更好,我的意思是认真的程序员会选择它的任何原因。

编辑:我最初要求数组/指针(Q1),但我的意思是 数组/数组指针

注意:请注意,这里的问题是传递与函数期望的维数不同的维数数组。在这方面,非常欢迎对标题进行编辑或提出建议。

最佳答案

@Gabriel,这看起来是一个有趣的问题,但我只提出了部分答案并制作了这个维基。 ***可能还需要工作。祝你好运。

回想一下,维度可能为 1,因此 quantity/(* dimSize) > 1 不足以进行测试。

这使用了level:索引到dimSize而不是quantity

void goesThrough(void * anArray, size_t * dimSize, size_t level, void (*aFunction)(int)) {
  if (level > 1) {
    for (size_t index = 0; index < *dimSize; index++) {
      void *(*a)[*dimSize];  // ***
      a = anArray;
      goesThrough(a[index], dimSize + 1, level - 1, aFunction);
    }
  } else if (level > 0) {
    int *a = anArray;
    for (size_t index = 0; index < *dimSize;index++) {
      aFunction(a[index]);
    }
  }
}

关于c - 如何将多维指针/数组传递给递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48534172/

相关文章:

c - 技巧 C 编译器将整个结构分配给零,没有 for 循环

c - C 中的单词替换,而不是子字符串

c - 如果我们改变 char* ptr = ; 指针指向的地址会改变吗?

c - 用 8 位整数替换部分 16 位整数

javascript - 如何修改此代码以在 ES6 中启用尾调用优化?

algorithm - 在 Clojure 中实现 Minimax 算法 - 具有多个递归调用的条件函数

c - 快速解决死锁?

C 程序每次打印 0.00000 但返回正确答案

c++ - 这个指针到底发生了什么

javascript - 使用 PHP 为目录中的所有 JavaScript 文件递归生成脚本标签