[英]Assign and dereference void * to an array pointer in C
I have a pointer to array of fixed size integer elements. 我有一个指向固定大小整数元素数组的指针。 After populating that array, I assigned it to void *pBuff.
填充该数组后,我将其分配给void * pBuff。 Later on, I need to access array elements through void pointer which I failed in doing so.
稍后,我需要通过失败的void指针访问数组元素。
Here is the code using C: 这是使用C的代码:
void * pBuff = NULL;
int
set_data(void *pBuff)
{
int ptr = 10, i;
int phy_bn[8] = {0};
int (*pPB)[8];
for(i=0; i<8; i++){
phy_bn[i] = ptr;
}
pPB = &phy_bn;
pBuff = pPB;
return 0;
}
int main()
{
int i;
set_data(&pBuff);
for(i =0 ; i <8; i++){
printf("\ndata : %d\n", *(int *)pBuff[i]);
}
return 0;
}
It prompts an error cast of 'void' term to non-'void' against *(int *)pBuff[i]. 它提示对*(int *)pBuff [i]进行从“无效”项到非“无效”的错误转换。
Any help will be really appreciated. 任何帮助将不胜感激。
Thanks, 谢谢,
-Sam -山姆
Apart from the fact that you need to use: 除了需要使用以下事实:
((int*)pBuff)[i]
What you have in your code is Undefined Behavior . 您的代码中有未定义的行为 。
pBuff = pPB;
pBuff
points to a array which is local to the function and its lifetime does not exist beyond the function scope. pBuff
指向函数本地的数组,并且其生存期不超出函数范围。 So you have a pointer pointing to something that does not need to exist but may seemingly exist sometimes. 因此,您有一个指针指向不需要存在但有时似乎存在的东西。
You should probably dereference with *
or []
, not both at the same time :-) 您可能应该使用
*
或[]
取消引用, 而不是同时取消引用:-)
If your intent is to get the integer at that i
position of a void pointer which points to int
s, use: 如果您打算在指向
int
的void指针的i
位置获取整数,请使用:
((int*)pBuff)[i]
The ((int*)pBuff)
turns pBuff
into a pointer to an integer and the [i]
following that grabs the i
'th integer at that location. ((int*)pBuff)
将pBuff
变成一个指向整数的指针, pBuff
的[i]
在该位置获取第i
个整数。
So your loop would be: 因此,您的循环将是:
for (i = 0 ; i < 8; i++)
printf ("\ndata : %d\n", ((int*)pBuff)[i]);
Another thing you should probably watch out for is returning pointer to stack-based variables. 您可能需要注意的另一件事是返回指向基于堆栈的变量的指针。 Those variables disappear when the function exits at which point dereferencing pointers to them is undefined behaviour.
当函数退出时,这些变量消失 ,此时,取消引用它们的指针是未定义的行为。
pBuff[i]
is illegal, since pBuff
is a void*
. pBuff[i]
是非法的,因为pBuff
是void*
。 It's a matter of operator precedence: 这是运算符优先级的问题:
((int *)pBuff)[i]
You don't need to dereference pBuff
again with the first *
because [i]
already does that. 您不需要再次用第一个
*
取消引用pBuff
,因为[i]
已经这样做了。
It should be 它应该是
void * pBuff = NULL;
int
set_data(void *pBuff)
{
int ptr = 10, i;
int *phy_bn = (int*)malloc(sizeof(int)*8);
//this is needed so that it is valid for pBuff to point phy_bn even if it is getting out of scope
for(i=0; i<8; i++){
phy_bn[i] = ptr;
}
pBuff = phy_bn;
return 0;
}
int main()
{
int i;
set_data(&pBuff);
for(i =0 ; i <8; i++){
printf("\ndata : %d\n", ((int*)pBuff)[i]);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.