0

Why we can decalre a variable as "void* x" but not "void x"? Why is "void* x" useful?

example:

int main()
{
    void* a;
    return 0;
}

The above code compiles and runs sucessfully

int main()
{
    void a;
    return 0;
}

The above code gets the following compile error:

b.c:6:10: error: variable has incomplete type 'void'
    void a;
         ^
1 error generated.
Lusha Li
  • 319
  • 3
  • 11

1 Answers1

1

I think it is because void is generally used as a return type for functions to indicate that there is no return value.

Void* is actually incredibly useful! Void* is used as a return type for memory functions like malloc() and calloc() because it allows them to manipulate any data type. Additionally, void* can be used to create generic functions. An often cited example of this is: void qsort (void* base, size_t num, size_t size, int (*comparator)(const void*,const void*))

This is a generic function implementing quicksort. The comparison function in this case uses void* pointers to suggest it can compare any data type.

user366608
  • 11
  • 2