c - 函数调用,将其 void * 参数转换为任何其他类型

标签 c casting void-pointers

有一个关于堆栈溢出的问题 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/

相关文章:

c - 段错误(核心转储)是什么意思? (快速排序代码)

c++ - 如何区分来自同一子网和不同 IP/用户的 sockaddr_in 结构

c++ - timeval 到字符串(在两者之间转换)

php - 如何转换 bigint 以防止 php 中的 sql 注入(inject)?

将 int 转换为 double 将返回 #INF00

C语言 : void *x = &x compiles and runs without declaring x beforehand

在释放内存之前转换为 void *(C 编程)

c++ - 我如何在 void* 和 boost shared_ptr 之间进行转换

c - 读取多行输入并将整数保存到数组中

c - dbx:警告:使用 srcline 信息进入函数