c - 如何获得指针指向的二维数组的宽度/高度?

标签 c arrays pointers multidimensional-array

如果我有这个引用变量:

float* image

如何在 C 中获取此图像的长度? length = (width * height) 但我怎样才能得到这个值呢?

最佳答案

float * image

简单地指向一个 float 。它也可以与数组语法一起使用——即 image[n] 从图像的位置获取第 n 个 float 。人们会使用指针和 malloc 来创建一个动态的 float 数组。但是,没有与数据本身存储的大小相关的信息。这是 C 中编码人员必须关心的细节。通常在 C 中的这些情况下,当您在函数中传递这样的指针时,您还会传递一个伴随的大小,即:

void Foo(float* image, size_t numFloatsInImage)

听起来 image 可能指向被视为二维数组的连续内存块。那是有宽度和高度的东西。因此,您可能有类似这样的“3x3”图像,而不是严格的 numberOfFloats:


    image ->  0  1  2  3  4  5  6  7  8
              0  0  0  1  1  1  2  2  2

There's a total of 3x3 == 9 floats here with the first 3 corresponding to row 1, the next 3 row 2, and the last one as row 4. This is simply a single dimensional array used to represent 2d data.

Like I said before, this is a detail of how you've decided to use the language and not a part of it. You'll have to pass along the width/height with the pointer for safe use:

void Foo(float* image, size_t width, size_t height)

您也可以通过简单地创建一个结构来存储图像来避免这种情况,确保始终正确地初始化/维护宽度和高度

 struct
 {
     float* image; // points to image data
     size_t width;
     size_t height;
 };

然后总是将结构传递给像 foo 这样的函数

另一个技巧可能是过度分配 float 以将宽度和高度存储在缓冲区本身中:

 float* image = malloc(width*height + 2);
 image[0] = width;
 image[1] = height;
 // everything past image[2] is image data

无论如何,有这些和许多其他特定于实现的方法来存储/传递此数据。给你这个指针的人应该告诉你如何获得长度/高度并告诉你如何使用指针。 C 无法弄清楚它是如何完成的,它是一个实现决定。

关于c - 如何获得指针指向的二维数组的宽度/高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7726196/

相关文章:

c++ - ** 和 * [] 一样吗?

c - 从 C 中的数据包中读取未初始化的无符号 int 数组

c - 文件读写模式 "r+"C 中的意外行为

c - 将数组(不是指针)传递给 c 中的结构

javascript - 从对象内的 JavaScript 数组中获取第一个值

c - 指针和多维数组

C++。如何将 const_cast 指针指向成员函数?

c - 在linux中为正在运行的程序设置环境变量

c - 如何将执行命令的结果从服务器发送到客户端?

arrays - 在数组上调用 toString - FindBugs