提问人:Dominykas 提问时间:2/28/2022 最后编辑:WhozCraigDominykas 更新时间:2/28/2022 访问量:120
*(int *)foo VS (int *)*foo。这两者有什么区别?
*(int *)foo VS (int *)*foo. Whats the difference between these two?
问:
我正在从事 RTOS 项目,我正在尝试将类型转换为 void 指针的结构类型传递给线程函数,并使用类型转换为相同的结构类型来取消引用该 void 指针。尝试以这种方式执行此操作时,我遇到了错误。然后在互联网上找到使用,但它没有解释区别以及它为什么有效(eUartDriver_t*) *args
*(eUartDriver_t*) args
答:
1赞
Eric Postpischil
2/28/2022
#1
据推测,它被声明为 .该表达式的意思是“事物指向”,因此将是一个 ,但不是可用的类型。糟糕的代码也是如此,编译器抱怨。args
void *
*args
args
*args
void
void
*args
(eUartDriver_t *) args
说“将 的值转换为 ”。该类型是指向 .这种转换的结果是指向 的指针,因此应用 ,如 中的 ,指的是 ,它是一个可用的类型。args
eUartDriver_t *
eUartDriver_t
eUartDriver_t
*
* (eUartDriver_t *) args
eUartDriver_t
评论
0赞
Dominykas
2/28/2022
所以表达式 (eUartDriver_t *) *args 在 C 中根本不有效?
0赞
Sir
2/28/2022
#2
@UnholySheep
操作顺序很重要。*args 取消引用指针,因此之后可能无法将其转换为另一个指针类型(因为结果可能不是指针类型)
#include <stdio.h>
int main()
{
//Consider integer:
int x;
//And pointer to it.
int *p= &x;
//These expressions
p; &x;
//are of type int*, which means the dereferencing operator can be used on these.
//This is legal:
*p; *(&x); p[0];
//Pointer casting <==> reinterpretation of pointer (address)
//These expressions are almost the same (have the same values and storage space)
(int*)p; (char*)p; p; (void*)p;
/*The only difference is in dereferencing or artmetics, which must happen
AFTER the pointer is known as (new) type pointer.
So once you've got this expression:*/
(char*)p;
//or new variable:
char *newP= (char*)p;
//or macro:
#define newP (char*)p
//THAN you can do derefrencing with proper use of operators *ptr or ptr[offset]
*newP; *((char*)p); newP[0]; ((char*)p)[0];
}
评论
args
*args