[英]Cast void* to array of struct
I have a vector of RGB data.我有一个 RGB 数据向量。
vector<int> image({1,1,1, 2,2,2, 3,3,3 , 4,4,4});
I want to flip this image horizontally (about the center column).我想水平翻转这个图像(关于中心列)。
to perform flip operation, I have created a function为了执行翻转操作,我创建了一个函数
flip(void* image, int rows, int cols)
where i would like to perform flip, but keep individual triplets of RGB intact我想在那里执行翻转,但保持 RGB 的单个三元组完好无损
So I created a所以我创建了一个
struct color{
char r;
char g;
char b;
};
and calling the function as并将函数调用为
int main(){
vector<int> image({1,1,1, 2,2,2, 3,3,3 , 4,4,4});
flip(&image[0],rows,cols);
}
but casting void* to struct color[] raises compilation error.但是将 void* 转换为 struct color[] 会引发编译错误。 How can I proceed around this ?
我该如何解决这个问题?
You can't cast to an array in C++.您不能在 C++ 中强制转换为数组。 You'll have to use a pointer.
您将不得不使用指针。
struct color* image = (struct color*)arr;
And for your purposes, this won't work right away.对于您的目的,这不会立即起作用。 You'll have to start using a vector of
char
not int
.您必须开始使用
char
而不是int
的向量。 This is because and int
is usually 4 bytes and a char is 1 byte.这是因为
int
通常是 4 个字节,而 char 是 1 个字节。 Trying to assign an int
to your struct (which is 3 bytes) wouldn't give you the result you expect.尝试为您的结构(3 个字节)分配一个
int
不会给您预期的结果。
Then you can access the pointer as an array.然后您可以将指针作为数组访问。 For example
image[0].r
would return the first value in the vector, and image[1].r
would return the fourth.例如
image[0].r
将返回向量中的第一个值,而image[1].r
将返回第四个值。 Just be careful to not go beyond the size of the vector.请注意不要超出向量的大小。
i changed the struct as我将结构更改为
struct color{
int rgb[3];
};
and和
struct color* image = (struct color*)arr;
provides an array of struct color which can be flipped keeping the rgb data intact.提供了一个 struct color 数组,可以翻转它以保持 rgb 数据完整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.