将指针传递给对象时类型转换为 (void *)

typecast to (void *) when passing pointer to object

考虑以下片段:

void my_func(int a, void *b);
...

struct my_struct s = { };
my_func(10, (void *)&s);

&s传递给函数时是否需要类型转换为(void *)

不,这不是必需的,它只是让代码更清楚地了解传递给函数的内容。

如果传递给函数的引用对象是 volatileconst - 通常具有不同的属性,您可能会收到警告,但有一些例外情况,您可能会收到警告。

void ee(void *q)
{
    pritntf("%p", q);
}

volatile int g;
const int f;

int main()
{

    ee(&g);
    ee(&f);
}

发出此警告:

<source>: In function 'main':

<source>:17:8: warning: passing argument 1 of 'ee' discards 'volatile' qualifier from pointer target type [-Wdiscarded-qualifiers]

     ee(&g);

        ^~

<source>:6:15: note: expected 'void *' but argument is of type 'volatile int *'

 void ee(void *q)

         ~~~~~~^

<source>:18:8: warning: passing argument 1 of 'ee' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]

     ee(&f);

        ^~

<source>:6:15: note: expected 'void *' but argument is of type 'const int *'

 void ee(void *q)

         ~~~~~~^

Compiler returned: 0

指向任何类型的指针可以自由转换为 void * 或从 void * 转换。

C standard 的第 6.3.2.3p1 节指出:

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

唯一需要强制转换的情况是,如果您将指针传递给像 printf 这样的可变参数函数,其中不能发生隐式转换,因为它不知道传入的确切类型是什么是。

请注意,与任何指针类型一样,在不进行强制转换的情况下传递给函数时,您不能 "remove" 诸如 const 之类的限定符。第 6.3.2.3p2 节指出:

For any qualifier q, a pointer to a non-q-qualified type may be converted to a pointer to the q-qualified version of the type; the values stored in the original and converted pointers shall compare equal.