#include <stdio.h>
#include <time.h>
#include <string.h>
char *matrix[10][10];
int main(void) {
int i;
char *list[4];
char *words[20] = {
" c a t ", " c a r ", " b e a r ", " s h i p ",
" m o u s e ", " b e a t l e ", " c o a t ", " n e s t ",
" i c e ", " s u g a r ", " b a c o n ", " f r o w n ",
" s m i l e ", " d e a d ", " f e a t h e r ", " g o a t ",
" h e n "," j e l l y "," k o a l a "," l i p s "
};
int length;
int num;
int k;
int m;
char otherString=0;
char *c;
int j;
int s;
int r;
char test[10];
char *token;
const char *search = " ";
char *empty = "";
int size;
int ans;
int x;
int y;
int pos;
int pos2;
int randRow;
int randColumn;
int chosen[10];
int random;
int d;
int ROWS = 10; // number of rows
int COLUMNS = 10; // number of columns
printf("\tA\tB\tC\tD\tE\tF\tG\tH\tI\tJ\n");
srand(time(NULL));
for (i = 0; i < 4; i++) {
printf( "\n" );
d = 0;
do {
random = (rand() % 20);
list[i] = words[random];
d = 0;
for (j = 0; j < i; j++) {
if (strcmp(words[random], list[j]) == 0)
d = 1;
}
} while (d);
}
token = strtok((words[random]), search);
while (token != NULL) {
length = strlen(words[random]);
for (k = 0; k < length; k++) {
matrix[i][k] = token;
token = strtok(NULL, search);
matrix [i][k] = token;
}
}
for (r = 0; r < 10; r++) {
printf("\n");
for (s = 0; s < 10; s++) {
//ans = strlen(matrix[r][s]);
/* if (ans == 0) {
c = 'A' + (rand() % 26);
matrix[r][s] = c;
}*/
printf("\t%s", matrix[r][s]);
}
}
getchar();
return 0;
}
基本上这个程序生成4个随机单词,但不能 重复
strtok
用来滑动单词以便它们 可以通过char将char输入到矩阵中。最后任何 矩阵中的空字符将被随机替换 字符。 但是strtok
正在生成运行时错误而我不是 确定如何检查null元素?
答案 0 :(得分:1)
在本声明中
token = strtok((words[random]),search);
function strtok
尝试更改数组元素words[random]
寻址的字符串文字。
字符串文字在C中是不可变的。任何更改字符串文字的尝试都会导致未定义的行为。
而不是指向字符串文字的指针数组
char *words[20]={" c a t "," c a r "," b e a r "," s h i p "," m o u s e "," b e a t l e "," c o a t "," n e s t "," i c e "," s u g a r "," b a c o n "," f r o w n "," s m i l e "," d e a d "," f e a t h e r "," g o a t "," h e n "," j e l l y "," k o a l a "," l i p s "};
你应该定义一个由字符串文字初始化的二维字符数组。例如
char words[20][20]={" c a t "," c a r "," b e a r "," s h i p "," m o u s e "," b e a t l e "," c o a t "," n e s t "," i c e "," s u g a r "," b a c o n "," f r o w n "," s m i l e "," d e a d "," f e a t h e r "," g o a t "," h e n "," j e l l y "," k o a l a "," l i p s "};
答案 1 :(得分:0)
token = strtok((words[random]),search); while(token!=NULL) { length=strlen(words[random]); for( k=0;k<length;k++){ matrix [i][k]=token; token = strtok(NULL, search); matrix [i][k]=token; } }
这是混乱而不是你想要的。将其改为直线,e。 G:
for (k = 0, c = words[random]; token = strtok(c, search); c = NULL, ++k)
matrix[i][k] = token;