char* matrix [10][10]; //matrix to put words in (all elements are equal to 1 at this point)
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 "
}; // 4 of these words will be randomly chosen
for( i=0;i<4;i++){
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);//making sure there are no duplicate words
strcpy(temp, words[random] );
length=strlen(temp); //length of word
printf("temp:%s",words[random]);
ans=(length/2);// length divided by 2 to remove spaces
size=(9-ans);// number of columns-word length
emptyD=0;
do{
x=(rand()%10);//generates a random co-ordinate
emptyD=0;
for(k=0;k<ans;k++){// for loop starting from zero till the length of word
if(strcmp(matrix[x+k][x+k],"1")==0)
emptyD=1; //checks whether the matrix element is equal to 1
}
} while(emptyD || x>size);
}
基本上我在这里要做的就是用文字填充矩阵 对角放置。为了避免与我设置整体的其他单词发生冲突 矩阵到1预先。每次一个角色进入该程序 检查元素空间是否等于1(表示它是空的 正)。但是这段代码工作不正常,仍然存在 碰撞。我将不胜感激任何帮助:)谢谢
答案 0 :(得分:1)
由于分配给ans
和size
的值,您可能面临的所有可能性。我相信matrix[10][10]
是造成问题的原因,因为对于x=9
和任何k>1
,您最终会访问数组边界。
您可能希望在比较后break
for(k=0;k<ans;k++)
循环并指定emptyD=1;
。但肯定需要检查访问数组索引。
或类似的东西应该有帮助
//no for loop required
if(strcmp(matrix[x][x],"1")==0) {
emptyD=1; //checks whether the matrix element is equal to 1
}
我不知道什么会结束while循环,因为你知道这些值更好并且它们经过测试:)