I am trying to shuffle the string elements in a 2d array, and I'm quite confused whether I should just shuffle the columns or all of them. Here's what I've done so far.
int main(int argc, char const *argv[]){
char words[4][20] = {"abc", "dec", "dsz", "dfas"};
for (int i=0;i<4;i ){
srand(time(NULL));
int r = rand() % 4;
int temp = i;
strcpy(words[i], words[r]);
strcpy(words[r],words[temp]);
}
for(int j=0;j<4;j ){
printf("Elements: %s\n",words[j]);
};
return 0;
}
However, this gives me a Trace/BPT trap: 5
error. Any helps would be appreciated.
CodePudding user response:
There are some ideas in your code, but there are some mistakes too. As some comments told, you should not initialize your random seed in your loop, but at the start of your program.
For your problem, it's probably because of strcpy
function. Indeed, sometimes r will be equal to i, meaning that when you call strcpy(words[i], words[r])
, both arguments actually refer to the same piece of memory, leading to your program crashing. This is because strcpy()
takes restrict pointers as arguments.
In order to understand why it does give you an error, you must understand what the restrict
keyword means in C : when two function parameters are made restrict, it means that they reference different pieces of memory. It's really great for compiler optimisation (to see more, you can have a look at this : Realistic usage of the C99 'restrict' keyword?.)
If you want your code to work, you must use a different char array as a buffer to hold your temp value.
It would then work like this :
srand(time(NULL));
char words[4][20] = {"abc", "dec", "dsz", "dfas"};
char buffer[20];
for (int i=0;i<4;i ){
int r = rand() % 4;
strcpy(buffer, words[i]);
strcpy(words[i], words[r]);
strcpy(words[r], buffer);
}
CodePudding user response:
Fisher-Yates Shuffle algorithm mentioned by jpmarinier. Thanks, and any feedbacks are welcomed.
srand(time(NULL));
char words[4][20] = {"abc", "dec", "dsz", "dfas"};
char copyWords[4][20];
for (int i=0;i<4;i ){
int r = rand() % 4;
while(1){
if (strcmp(words[r],"") != 0){
strcpy(copyWords[i], words[r]);
memset(words[r],0,sizeof(words[r]));
break;
}
else {
r = rand() % 4;
}
}
}