There are multiple errors and flaws in OPs code.
- array of strings:
const char *words = { "one", "two", "three", "four", "five", "six" };
Not sure how the compiler reads this (if not complaining). An array of C strings should be:
const char *words[] = { "one", "two", "three", "four", "five", "six" };
- magic number
for (int i=0; i<6; i++)
6
is a magic number which is considered as bad style. It's better to give it a name. Even better: the value can be determined by compiler which improves maintainability of code:
int n = sizeof words / sizeof *words;
for (int i = 0; i < n; ++i) {
- usage of
rand()
int r = (rand() % (6 - i)) + i;
rand()
is a pseudo random generator with certain limitations. It shouldn't be used with % n
. For certain n
s (e.g. 2), this may result into a rather non-random sequence. The cppreference doc. of rand()
gives a better example which I turned into a function:
int randomRange(int min, int max)
{
for (int range = max - min;;) {
int x = min + rand() / ((RAND_MAX + 1u) / range);
if (x < max) return x;
}
}
which is called
int r = randomRange(i, n);
- idiomatic swap
int temp = words[i];
If the type of array elements to swap is const char*
the temp
must be as well:
const char *temp = words[i];
words[i] = words[j];
words[j] = temp;
The complete sample code:
#include <stdio.h>
#include <stdlib.h>
int randomRange(int min, int max)
{
for (int range = max - min;;) {
int x = min + rand() / ((RAND_MAX + 1u) / range);
if (x < max) return x;
}
}
int main(void)
{
/* an array of strings */
const char *words[] = { "one", "two", "three", "four", "five", "six" };
/* let compiler determine size */
int n = sizeof words / sizeof *words;
/* shuffle */
for (int i = 0; i < n; ++i) {
int j = randomRange(i, n);
/* idiomatic swap */
const char *temp = words[i];
words[i] = words[j];
words[j] = temp;
}
/* print result */
const char *sep = "";
for (int i = 0; i < n; ++i) {
printf("%s%s", sep, words[i]);
sep = ", ";
}
/* done */
return 0;
}
Output:
six, three, one, two, four, five
Live Demo on coliru