从功能和语法上来说,原型为int foo(void)
和的函数之间是否有区别int foo(void *)
?
我知道,例如之间的差异,int bar(int)
以及int bar(int *)
-其中之一是寻找一个int,另一种是找一个int指针。void
行为是否相同?
foo(void)
和foo()
。
从功能和语法上来说,原型为int foo(void)
和的函数之间是否有区别int foo(void *)
?
我知道,例如之间的差异,int bar(int)
以及int bar(int *)
-其中之一是寻找一个int,另一种是找一个int指针。void
行为是否相同?
foo(void)
和foo()
。
Answers:
根据有关软件工程的答案, void
将根据其使用方式对其进行特殊处理。在C
和C++
,void
用于指示不存在数据类型的,而void *
用于指示一个指针,它指向在存储器中的某些数据/空间不具有一个类型。 void *
不能单独取消引用,必须先转换为其他类型。此强制转换不必在中显式C
,但必须在中显式C++
。(这就是为什么我们不强制转换malloc的返回值的原因void *
。)
与函数一起用作参数时,void
表示完全不存在任何参数,并且是唯一允许使用的参数。尝试像变量类型一样使用void或包含其他参数会导致编译器错误:
int foo(void, int); //trying to use "void" as a parameter
int bar(void baz); //trying to use "void" as an argument's type
main.c:1:8: error: 'void' must be the first and only parameter if specified
int foo(void, int);
^
main.c:2:14: error: argument may not have 'void' type
int bar(void baz);
^
同样,用类型声明一个变量也是不可能的void
:
int main(void) {
void qux; //trying to create a variable with type void
}
main.c:5:8: error: variable has incomplete type 'void'
void qux;
void
作为函数的返回值表示不会返回任何数据。由于无法声明类型的变量void
,因此即使使用void指针也无法捕获void
函数的返回值。
void foo(int i) { return; }
int main(void) {
void *j;
j = foo(0);
return 0;
}
main.c:5:5: error: assigning to 'void *' from
incompatible type 'void'
j = foo(0);
^ ~~~~~~
无类型void *
是另一种情况。空指针指示指向内存中某个位置的指针,但不指示该指针处的数据类型。(这是用于在C中实现多态性的功能,例如使用qsort()函数。)但是,使用这些指针可能很棘手,因为很容易将它们意外地转换为错误的类型。以下代码不会在中引发任何编译器错误C
,但会导致未定义的行为:
#include <stdio.h>
int main(void) {
double foo = 47.2; //create a double
void *bar = &foo; //create a void pointer to that double
char *baz = bar; //create a char pointer from the void pointer, which
//is supposed to hold a double
fprintf(stdout, "%s\n", baz);
}
但是,以下代码完全合法;向和从空指针进行强制转换永远不会更改其持有的值。
#include <stdio.h>
int main(void) {
double foo = 47.2;
void *bar = &foo;
double *baz = bar;
fprintf(stdout, "%f\n", *baz);
}
47.200000
作为函数参数,void *
它指示您所传入的指针处的数据类型未知,并且程序员(您)应自行决定如何正确处理该内存位置的内容。作为返回值,void *
表示所返回的数据的类型未知或为无类型,必须由程序进行处理。
int quux(void *); //a function that receives a pointer to data whose type is not known, and returns an int.
void *quuz(int); //a function that receives an int, and returns a pointer to data whose type is not known.
tl; dr void
在函数原型中表示“无数据”,表示没有返回值或参数,void *
在函数原型中表示“该函数给出的指针处的数据不具有已知类型”,并表示参数或返回值必须先将其指针转换为其他类型,然后才能使用该指针上的数据。
void * ... must be cast to another type first, but may be done so without an explicit cast.
在C ++中不正确。在C ++中,转换形式void*
必须是明确的。PS调用强制转换显式是多余的,因为根据定义强制转换是显式转换。