Stack Player
Stack Player

Reputation: 1490

Pointer to a void

inline int cmp (const void *a, const void *b)
{
  int aa = *(int *)a;
  int bb = *(int *)b;
  return (aa < bb) ? -1 : (aa > bb) ? 1 : 0;
}

This is a rather simple function that returns -1 if a is less than b, 0 if they are equal, and 1 if a is greater than b.

What are the properties of const void *? As I understood *(int *)a casts a to a pointer to an int and retrieves its content, and const void * points to memory that should not be modified while void * points to memory that could be modified, but what does it mean to point to a void? It is not like pointing to an int for example. I don't think I'm being clear. I just don't get the concept of pointing to a void. Can you help?

Upvotes: 0

Views: 163

Answers (4)

P0W
P0W

Reputation: 47844

void *a

void *b

Are generic pointer, its used in order to make the function generic, i.e. it can operate on any data type

Such prototype are used for qsort

int (*compar)(const void*,const void*) as a custom comparator

However in actual defining while comparison you still need to know the data type in advance.

As in your case they are of type int

Upvotes: 0

rmhartog
rmhartog

Reputation: 2323

void * is used as a pointer to anything, where the type it points to is unknown or does not matter. By casting it to int * you are making the assumption that they point to integers, which may be true in your use case, for example when passing a pointer to this function as a comparator for a collection of ints.

Note that casting to int * from const void * is bad style and should be avoided, cast to const int * instead.

Upvotes: 1

Mats Petersson
Mats Petersson

Reputation: 129524

In this case, void * means "points at something, not quite sure what". This is much more of a C style solution. In C++, I'd say the correct solution is:

template<typename T>
int cmp(const T *a, const T *b)
{
    return (*a < *b)? -1 : (*a > *b) ? 1 : 0;
}

or without pointers:

template<typename T>
int cmp(const T a, const T b)
{
    return (a < b)? -1 : (a > b) ? 1 : 0;
}

However, the C style solution may be useful in cases where you'd be using it for "C" style functions (qsort comes to mind - although in that particular case, I'd say std::sort is a better choice anyway).

Upvotes: 3

sr01853
sr01853

Reputation: 6121

Void pointers can be typecasted to any type of pointer. Or void pointers just point to a memory location without knowing what type it points to.

Upvotes: 0

Related Questions