[Solved] Shuffle character array in C


Having

char names[16][20] = ...;
char randomnames[16][20];

you cannot do

randomnames[i] = names[j];

but

char names[16][20] = ...;
char * randomnames[16];
...
randomnames[i] = names[j];

or

char names[16][20] = ...;
char randomnames[16][20];
...
strcpy(randomnames[i], names[j]);

Warning when I see your first version of the question you have to print names rather than randomnames, that means you need to modify randomnames and the char temp[20] clearly indicates you have to swap the names inside randomnames

So something like that :

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
  int i, j, k;
  char temp[20];
  char names[16][20] = { "Anne" , "Carmen" , "David" , "Jesmond" ,
                         "John" , "Joseph" , "Karen" , "Kevin" ,
                         "Manuel" , "Maria" , "Matthew" , "Michaela" ,
                         "Paul" , "Sandra" , "William" , "Yilenia" };

  //--------------------------- The Code between the dotted lines is the one I still need to write -----------------
  srand(time(NULL));

  for (i = 0; i < 16; i++) /* can be an other number of loop */
  {
    j = rand() % 17;
    k = rand() % 17;
    if (j != k) {
      strcpy(temp, names[j]);
      strcpy(names[j], names[k]);
      strcpy(names[k], temp);
    }
  }
  //---------------------------------------------------------------------------

  for (i = 0; i < 16; i++)
  {
    puts(names[i]);
  }
  getchar();
  return 0;
}

As you see I use all the variables and no additional ones.

Example of compilation and execution :

pi@raspberrypi:~ $ gcc -pedantic -Wall s.c
pi@raspberrypi:~ $ ./a.out
Sandra
John
William
Karen
Joseph
Kevin
Manuel
Carmen
Anne
Jesmond
Michaela
Maria
Paul
Matthew
David
Yilenia

6

solved Shuffle character array in C