[英]void* pointing to 2D array
I have a struct: 我有一个结构:
struct foo
{
void *param;
};
void main(){
foo object;
}
I need to make object.param point to a dynamically allocated 2D array. 我需要使object.param指向动态分配的2D数组。
I know this will obviously not work: 我知道这显然是不行的:
//CASE 1
pixel **buf = (pixel**)malloc(16*sizeof(pixel*));
for(int i=0; i<16;i++)
buf[i] = (pixel*)malloc(16*sizeof(pixel));
object.param = (void **)buf
This works: 这有效:
//CASE 2
pixel buf[16][16];
object.param = (void *)buf;
My question is: 我的问题是:
buf
interpreted as a pointer of type pixel
(when in fact buf
stores pixel*
) which allows it to be cast to a void*
? buf
解释为类型为pixel
的指针(实际上buf
存储pixel*
),因此可以将其转换为void*
? This should work fine: 这应该工作正常:
int main(){
struct foo object;
struct pixel **buf = malloc(10*sizeof(struct pixel*));
for(int i=0; i<10;i++)
buf[i] = malloc(10*sizeof(struct pixel));
object.param = buf;
}
The casts weren't necessary, and because this is C you need to use struct pixel
instead of pixel
. 强制转换不是必需的,因为这是C,所以您需要使用
struct pixel
而不是pixel
。
The second case works because you can cast any pointer to void*
. 第二种情况有效,因为您可以将任何指针强制转换为
void*
。
For the same reason, the first case will work if you do object.param = (void *)buf
, or object.param = buf
, as @Iskar comments. 出于同样的原因,如果您使用
object.param = (void *)buf
或object.param = buf
用作第一种情况。
Remember, a 2D array in C of type foo[M][N]
is really a 1D array of M×N elements and has type foo*
. 请记住,C语言中的
foo[M][N]
类型的2D数组实际上是M×N个元素的1D数组,类型为foo*
。 If you declare foo[10][3] a; foo *p = a;
如果声明
foo[10][3] a; foo *p = a;
foo[10][3] a; foo *p = a;
then foo[i][j]
and p[i*10+j]
mean exactly the same thing. 那么
foo[i][j]
和p[i*10+j]
意思完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.