c - 指向 3d 数组的指针

标签 c arrays pointers multidimensional-array

我想以一种可以用比原始数组小一维的方式对其进行索引的方式声明一个指向 3d 数组的指针,例如:ptr[i][j]。我正在使用一些结构,我希望在其中存储该指针,以便稍后可以访问它。

我已经使用二维数组完成了此操作,但我声明了一个指向二维数组的指针数组的指针:

typedef const unsigned char* ptrType;
const ptrType ptrArray[] = {...};

这就是我正在尝试的 3d 数组:

typedef const unsigned char** ptrType;

typedef struct structP
{
    ptrType arrayPtr;
};

主要是我正在做这样的事情:

struct structP test;
test.arrayPtr = *myThreeDArray; 

当尝试通过指针访问元素时,这是编译器允许我做的唯一事情:

&(test.arrayPtr[i][j]);

myThreeDArray 的定义如下:

const unsigned char myThreeDArray[2][23][25] = { ... };

按照所描述的方式执行此操作会在输出中产生意想不到的结果。一些垃圾值。

有什么想法可以以正确的方式做到这一点吗?

最佳答案

您似乎想要的是指向二维数组的指针

对于整数,这可能是这样的:

#include <stdio.h>

void print_3d(int (*p3d)[3][4])
{
    for (int i=0; i<2; ++i)
        for (int j=0; j<3; ++j)
            for (int k=0; k<4; ++k)
                printf("%d ", p3d[i][j][k]);
}

int main(int argc, char *argv[])
{
    int arr3d[2][3][4] = {
                          {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}},
                          {{13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}}
                         };

    int (*p_to_arr3d)[3][4] = arr3d;  // Get a pointer to int[3][4]
    print_3d(p_to_arr3d);             // Use the pointer
}

输出:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 

如果你正在处理字符串,它可能是这样的:

#include <stdio.h>

void print_3d(char (*p3d)[3][20])
{
    for (int i=0; i<2; ++i)
        for (int j=0; j<3; ++j)
            printf("%s ", p3d[i][j]);
}

int main(int argc, char *argv[])
{
    char arr3d[2][3][20] = {
                           {"this", "is", "just"},
                           {"a", "little", "test"}
                         };

    char (*p_to_arr3d)[3][20] = arr3d;    // Get a pointer to char[3][20]
    print_3d(p_to_arr3d);
}

输出:

this is just a little test

使用与上面相同的语法,您可以将指针存储在结构中:

struct myData
{
    char (*p_to_char_arr)[3][20];
    int (*p_to_int_arr)[3][4];
};

关于c - 指向 3d 数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405529/

相关文章:

c++ - 指针指针方法 C++

c - C 语言的字典顺序

c程序在循环程序时重复游戏的尝试

arrays - 返回一个范围内的整数数组

python - (Numpy) bool 数组的索引列表

c++ - 函数的 std::vector

c++ - c/c++微秒时间戳

c - 尝试根据数字是否在数组中打印 1 或 2

java - 使用单个低位数字时,最小值和最大值不能正常工作

C - 堆上的缓冲区在 EXEC 后不会丢失,而是保存在堆栈上