简体   繁体   English

返回指向多维数组的指针

[英]Returning a pointer to multidimensional array

Let's say I'm creating a multidimensional array as follows. 假设我要创建一个多维数组,如下所示。

const int array_temp[3][2][1] = {
    [0] = {{0}, {1}},
    [1] = {{2}, {3}},
    [2] = {{4}, {5}},
};

This array represents 3 tables of 2 entries in each table. 该数组表示3个表,每个表2个条目。

How would I return a pointer to the start of one of the 3 tables? 我如何返回一个指向3个表之一的开始的指针? Would it be as follows? 会如下吗?

return (void *)&array_temp[idx][0][0];

In a 3D case, derefernce the pointer name once leads us to the Zeroth row. 在3D情况下,一旦取消引用指针名称,便会将我们引向第零行。 This means that adding idx to the dereferenced name would lead us to the idx'th row(Where idx>=0) 这意味着将idx添加到已取消引用的名称将导致我们进入第idx行(其中idx> = 0)

return ((*array_temp)+idx);

But be sure that you don't declare the array inside the function. 但是请确保不要在函数内部声明数组。 As its duration is till the function ends 由于其持续时间到功能结束

Try return array_temp[idx] . 尝试return array_temp[idx] the return array_temp[idx][0][0] will return a specific content not the (container) array itself. return array_temp[idx][0][0]将返回特定的内容,而不是(容器)数组本身。

This example is self explanatory I think 我认为这个例子不言自明

#include <stdio.h> 

char arr[4][5][6];



int main(int argc, char *argv[]) {

    printf("%d\n\r", sizeof *(arr));
    printf("%d\n\r", sizeof *(arr[0]));
    printf("%d\n\r", sizeof *(arr[0][0]));
    printf("%d\n\r", sizeof *(&arr));
    printf("%d\n\r", sizeof *(&arr[0]));
    printf("%d\n\r", sizeof *(&arr[0][0]));

}

And the result: 结果:

30
6
1
120
30
6

Nothing to add I think 我认为没什么可补充的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM