如果我有这个参考变量:
float* image
我怎样才能用C来表示这张图片的长度?但是我怎样才能得到这个值呢?
最佳答案
float * image
只需指向一个浮点数。它还可以与数组语法一起使用——即从图像的位置获取第n个浮点。人们将使用指针和malloc创建浮动的动态数组。但是,没有与数据本身存储的大小相关联的信息。在C语言中,这是编码人员必须关心的一个细节。通常在C语言中,当您在函数中传递这样一个指针时,也会传递一个伴随的大小,即:
void Foo(float* image, size_t numFloatsInImage)
听起来好像
image[n]
可能指向一个被当作2d数组处理的连续内存块。那是有宽度和高度的东西。因此,您可能会得到类似于“3x3”图像的内容,而不是严格意义上的浮点数: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/