I got all excited until I read that all you're doing is shuffling strings. ;) The inefficient way is to swap the strings directly:
void shuffle(char array[][20], size_t n)
{
if (n > 1) {
size_t i;
for (i = 0; i < n - 1; i++) {
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
char t[20];
strcpy(t, array[j]);
strcpy(array[j], array[i]);
strcpy(array[i], t);
}
}
}
A much faster method is to use an array of char pointers and swap the pointers. That way the swap is fast, and as an added benefit of retaining the original order of the array:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void shuffle(char **array, size_t n)
{
if (n > 1) {
size_t i;
for (i = 0; i < n - 1; i++) {
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
char *t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
int main()
{
char a[5][20] = {
"I","want","a","pickle","baby"
};
char *b[5];
int i;
srand((unsigned)time(NULL));
for (i = 0; i < 5; i++)
b[i] = &a[i][0];
for (i = 0; i < 5; i++)
printf("%s\n", a[i]);
printf("\n");
shuffle(b, 5);
for (i = 0; i < 5; i++)
printf("%s\n", b[i]);
printf("\n");
for (i = 0; i < 5; i++)
printf("%s\n", a[i]);
return 0;
}
Another benefit is that you don't have to specify the size of the second dimension because you can pass an array of pointers instead of an array of arrays. :)