c++ - 在 C++ 中创建一个指向 3 维数组的指针

标签 c++ c arrays pointers

我看过这个similar question ,但它不起作用。

在外部,在 Filter.h 中我有

struct test{
    unsigned char arr[3][8192][8192];
}

我已经初始化了这些结构之一,如果我使用,我的代码可以正常工作:

initialized_test_struct -> arr[2][54][343]

但是,我想缓存一个指向这个数组的指针:

unsigned char (*new_ptr)[8192][8192] = &(initialized_test_struct -> arr)
assert initialized_test_struct -> arr[2][54][343] == new_ptr[2][54][343]

但是当我尝试这样做时,我得到:

cannot convert ‘unsigned char ()[3][8192][8192]’ to ‘unsigned char ()[8192][8192]’ in initialization

当我尝试时:

unsigned char (*colors)[3][8192][8192] = &(input -> color);

我得到了错误的数据类型(使用时):

error: invalid operands of types ‘unsigned char [8192]’ and ‘char’ to binary ‘operator*’

我怎样才能做到这一点?

最佳答案

这应该有效:

#include <iostream>

struct test{
    unsigned char arr[3][8192][8192];
};

int main()
{
    test initialized_test_struct;
    unsigned char (*new_ptr)[8192][8192] = initialized_test_struct.arr;
    return 0;
}

无论何时在表达式中使用数组变量,它都会被转换为指向数组元素类型的指针。例如,

int a[3] = {1,2,3};
int* b = a; // this is ok

但是,如果我们这样做

int a[2][1] = {{1}, {2}};
int* b = a; // this will fail, rhs has type int(*)[1], not int*

我们必须做

int a[2][1] = {{1}, {2}};
int (*b)[1] = a; // OK!

如果你有一个 C++11 兼容的编译器,你可以简单地做

auto new_ptr =  initialized_test_struct.arr;

编译器会为您处理类型推导并将 auto 替换为正确的类型。

关于c++ - 在 C++ 中创建一个指向 3 维数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29311787/

相关文章:

c++ - 如何实例化类的公共(public)成员并将其作为 std::promise 返回?

c++ - 将 C++ 变量从类传递给 C 函数

c++ - 测量函数在整个生命周期内在堆和堆栈上分配的总空间

c - 逻辑错误-插入排序

php - 在 PHP 中使用整数过滤数组值

javascript - 使用数组代替 Set

c++ - 哪个 gcc 和 g++ 版本支持 c 和 c++ 的哪个标准?

c - 如何将 unsigned char * 转换为 QString

c - 如何使用 snprint() 函数追加字符串

创建结构数组