I found on this thread the following function to shuffle any kind of data types:
#define NELEMS(x) (sizeof(x) / sizeof(x[0]))
/* arrange the N elements of ARRAY in random order.
* Only effective if N is much smaller than RAND_MAX;
* if this may not be the case, use a better random
* number generator. */
static void shuffle(void *array, size_t n, size_t size) {
char tmp[size];
char *arr = array;
size_t stride = size * sizeof(char);
if (n > 1) {
size_t i;
for (i = 0; i < n - 1; ++i) {
size_t rnd = (size_t) rand();
size_t j = i + rnd / (RAND_MAX / (n - i) + 1);
memcpy(tmp, arr + j * stride, size);
memcpy(arr + j * stride, arr + i * stride, size);
memcpy(arr + i * stride, tmp, size);
}
}
}
I have been testing and it seems to work fine but I'm having a hard time understanding how and why it works.
- How and why doesn't it swap an element of the array directly on
array
- How come it is possible to assign array to a char*:
char *arr = array;
- The offset
i * stride
orj * stride
in memcpy functions is bigger than the total size of the array (sizeof(array)
). How come the pointer arithmetic works here?