【问题标题】:Passing 2D Const Array Using Double Pointer使用双指针传递 2D 常量数组
【发布时间】:2018-10-15 05:55:58
【问题描述】:

我想使用双指针传递一个 2D 常量数组,但我得到一个编译器错误。

const unsigned char sizex=2;
const unsigned char sizey=5;
const unsigned char arr[sizex][sizey] ={
  {1,2,3,4,5},
  {6,7,8,9,10}};

void foo (const unsigned char **a, const unsigned char x, const unsigned char y) {
  int i,j;
  for(i=0;i<x;i++) {
    for(j=0;j<y;j++) {
      Serial.println(a[i][j]);
    }
  }
}

void main() {
  foo(arr,sizex,sizey);
}

错误

无法将 'const unsigned char (*)[5]' 转换为 'const unsigned char**' 对于参数 '1' 到 'void foo(const unsigned char**, unsigned char, 无符号字符)'

void foo (const unsigned char a,[][5] const unsigned char x, const unsigned char y) 有效,但我不想将 [5] 硬编码到代码中。

有什么建议可以解决这个问题吗?

【问题讨论】:

  • 数组数组与指向指针的指针相同。参见例如this old answer of mine 解释原因。
  • 谢谢。那么我的问题是如何在不明确指定大小的情况下传递数组数组?

标签: c++ arrays multidimensional-array constants


【解决方案1】:

在 C 中,一种解决方案是使用variable-length arrays,这可以通过切换参数的顺序来完成:

void foo (const unsigned char x, const unsigned char y, const unsigned char a[x][y]) { ... }

但是这是有问题的,因为 Arduino 实际上是使用 C++ 而不是 C 进行编程的,并且 C++ 没有可变长度数组(即使某些编译器可能已将其添加为扩展)。

您当然可以直接使用全局常量(和数组)而不是作为参数传递,除非您需要对不同大小的不同数组使用相同的函数。适用于 C 和 C++。需要注意的是,应尽可能避免使用全局变量。

解决您的问题的自然 C++ 解决方案是使用 std::vector,但我不知道有多少 C++ 标准库可用(如果有的话)。您或许应该研究一下the Arduino documentation,看看是否有其他容器类型可供您使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多