gpt4 book ai didi

c - 函数参数和参数中的隐式指针转换

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:12 24 4
gpt4 key购买 nike

如果2个函数定义是:

    void func(struct Node *arg){...}

void func2(void *arg){
func(arg);
...
}

但是他们的名字是这样的:

    struct Node *node = (char *)malloc(6);
func2(node)

我认为 node 被隐式转换为 void* 然后转换为 struct Node*,所以我不需要做类似的事情:

    func2((void *)node);
or func((struct Node *)arg);

我的理解正确吗?

最佳答案

  1. 没有“隐式转换”这样的东西。有显式类型转换(casting)和隐式类型转换(type coercion or promotion)。

  2. 由于 void * 与任何 data 指针类型兼容(如果您的实现符合 POSIX,那么它也与函数指针兼容),您的假设是对的:

T *object = malloc(size);

是正确的,无论 T 表示什么类型。当然,这同样适用于函数参数。

有些人(包括我自己)甚至认为 casting in this case is dangerous, decreases readability and should be avoided .

关于c - 函数参数和参数中的隐式指针转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16697289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com