有一个关于堆栈溢出的问题 Why type cast a void pointer? 我想在评论中提出相关问题,但我不允许,因为我是这里的新手。 我的问题在Guillaume给出的第二个答案中,有这个功能。
void some_function(void * some_param) {
int some_value = *((int *) some_param); /* ok */
我可以这样做吗
// function defination
void some_function(void * some_param) {
int some_value = *some_param;
// calling function, casting in argument
some_function((int *) some_param);
谢谢
最佳答案
在此通话中
some_function((int *) some_param);
函数参数隐式转换为参数类型,即void *
。所以转换是多余的,函数内的这条语句
int some_value = *some_param;
无效。
根据C标准(6.3.2.2无效)
1 The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way, and implicit or explicit conversions (except to void) shall not be applied to such an expression. If an expression of any other type is evaluated as a void expression, its value or designator is discarded. (A void expression is evaluated for its side effects.)
还有这个表达式
*some_param
函数内的类型为 void
void some_function(void * some_param) {
int some_value = *some_param;
//...
}
至于问题
During function call, can I cast its void * argument to any other type in ANSI C
您可以将 void *
类型的指针分配给指向任何其他类型的对象的指针,而无需进行强制转换,也可以将 void *
类型的指针强制转换为任何其他类型的对象。对象指针类型..
关于c - 函数调用,将其 void * 参数转换为任何其他类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58716231/