I tried creating an array of ten random strings that would print directions randomly. Such as first time "up down right ... rot_x" and second time "forward rot_y up ... down" etc. I tried using a char* pc and allocating memory for it with memset but that didn't work so I tried the following code but I'm getting weird output. How can I fix this?
int main()
{
int r_num;
char r_arr[10][10];
for (int i = 0; i < 10; i++)
{
r_num = rand() % 10;
switch(r_num)
{
case 0: strcpy(r_arr[0], "up");
break;
case 1: strcpy(r_arr[1], "down");
break;
case 2: strcpy(r_arr[2], "left");
break;
case 3: strcpy(r_arr[3], "right");
break;
case 4: strcpy(r_arr[4], "rot_x");
break;
case 5: strcpy(r_arr[5], "rot_y");
break;
case 6: strcpy(r_arr[6], "rot_z");
break;
case 7: strcpy(r_arr[7], "forward");
break;
case 8: strcpy(r_arr[8], "back");
break;
case 9: strcpy(r_arr[9], "reset");
break;
default:
fprintf(stderr, "Cannot process input/n");
}
}
for (int i = 0; i < 10; i++)
{
printf("%s ", r_arr[i]);
}
return 0;
}
here's my output:
up ?V? left right rot_x ?V? forward back reset
r_arryou write. Some of them may never get written to.strcpy()here. Why not just create an arraychar *r_arr[10]and fill each value with a pointer to one of your ten strings?