Search code examples
cpointersvoid

How does a function with a void array pointer argument know the size of array elements?


Page 121 of K&R lists the following function for swapping two array elements:

void swap(void *v[], int i, int j)
{
    void *temp;

    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

I don't understand how indexing into the array can work when the array does not have a type.

As far as I am aware, types do not exist at runtime and there is no guarantee that this function would be compiled along with the code that uses it.

How then is it possible for this function to correctly perform array indexing when an array containing values of any size could be passed to it?

In other words, if I passed a long array to this function, how would it know that v[i] would be located at v + sizeof(long) * i when it does not know the type of the array?


Solution

  • The array does have a type. It is an array of void *, and a void * is a fully defined type, unlike void.

    So what this function is doing is swapping a pair of void * in the array.

    If v was defined as void * instead of void *[], then you would have a problem.