what is the practical use of void datatype and void pointer?

风格不统一 提交于 2019-12-11 19:18:47

问题


Void variable has nothing to do and also void pointer can only be pointed with casting. So void pointer is used when we actually don't know where and of which data type we want to point. But what is of void variable?

Any practical example?


回答1:


In C void can't be considered a data type, it is a keyword used as a placeholder in place of a data type to show that actually there is no data.

For example consider the function void f(void);. Here the keyword void is used to mean the absence of any parameters passed and returned values.

But void *ptr; is different in meaning.

This declares a pointer without specifying which data type it is pointing to.




回答2:


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);
}



回答3:


void pointers are very useful for memory allocation purposes, when we don't have knowledge about the exact datatype. Try to write your own malloc to get sense of void *.

or read http://www.cplusplus.com/reference/cstdlib/malloc/




回答4:


There is no void variable, as marko Topolnik states in his comment.

Void pointers are used in C/C++ to point to something unspecified. The keyword is also used (and in C# and other languages) to mark methods that do not return a value. So I think you are thinking:

void method();

is returning something of type void, which it is not. It is not returning anything.




回答5:


They're useful in a generic interface, like the classic 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.



来源:https://stackoverflow.com/questions/16644914/what-is-the-practical-use-of-void-datatype-and-void-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!