0

void 变量无关,而且 void 指针只能通过强制转换来指向。因此,当我们实际上不知道要指向的位置和数据类型时,会使用 void 指针。但是什么是 void 变量?

有什么实际的例子吗?

4

5 回答 5

1

在 Cvoid中不能被认为是一种数据类型,它是一个关键字用作占位符来代替数据类型,以表明实际上没有数据。

例如考虑函数void f(void);。这里关键字 void 用于表示没有任何参数传递和返回值。

void *ptr;意义不同。

这声明了一个指针,但没有指定它指向的数据类型。

于 2013-05-20T07:56:12.433 回答
1

There is no void variable, but there are void pointers. As the others have mentioned a lot, I would like to remind you to type cast before using void pointers.

float generic_add(void *n1, void *n2){
    return *((int *) n1) + *((float *) n2);
}
于 2013-05-20T09:01:21.870 回答
0

当我们不知道确切的数据类型时,void 指针对于内存分配非常有用。尝试编写自己的 malloc 以了解 void *.

或阅读 http://www.cplusplus.com/reference/cstdlib/malloc/

于 2013-05-20T07:55:16.803 回答
0

void正如 Marko Topolnik 在他的评论中所说,没有变量。

Void指针在 C/C++ 中用于指向未指定的东西。该关键字还用于(以及在 C# 和其他语言中)标记不返回值的方法。所以我想你在想:

void method();

正在返回 type 的东西void,但事实并非如此。它没有返回任何东西。

于 2013-05-20T07:56:41.320 回答
0

它们在通用接口中很有用,比如经典的qsort.

void
 qsort(void *base, size_t nel, size_t width,
     int (*compar)(const void *, const void *));

http://www.manpagez.com/man/3/qsort/

The void return type identifies this as a procedure rather than a function, because it returns no data at all (of any type). The void *s can point to anything at all, but the compar function has to cast them appropriately in order to use them.

于 2013-05-20T07:58:15.687 回答