我正在尝试创建一个零维数组,并在其中生成一个随机数组。但是当我编译它时,它用随机列填充随机列。我看到错误是在循环中写入地图,因为如果我把所有for ( j = 0; j <= c; j++ )
放在外面和内部我改为for (i = 0; i <= l; i++ )
而不是填充列,它将填充该行。不幸的是,虽然我不知道如何解决它。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main (){
int l = 20;
int c = 20;
int map[l][c];
int i, j;
srand(time(NULL));
int r_colum;
int r_line;
r_coluna = rand() % c;
r_linha = rand() % l;
/* Create a map of 0 */
for (i = 0; i <= l; i++ ) {
for ( j = 0; j <= c; j++ )
{
map[i][j] = 0;
}
}
printf("%d %d \n", r_colum, r_line);
map[r_linha][r_coluna] = 1;
/* Write the map*/
for(i = 0; i < l; i++) {
for(j = 0; j < c; j++) {
printf("%d ", map[i][j]);
}
printf("\n");
}
return 0;
}
错误输出:1应该在第16行第4列,而不是在所有列中。
答案 0 :(得分:1)
最好不要删除可变长度数组,并使用简单的#define
(修复后,复制/粘贴错误r_coluna
和r_linha
)。尝试:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define MSIZE 20
int main (void)
{
int map[MSIZE][MSIZE] = ;
int i, j, r_colum, r_line;
srand (time (NULL));
r_colum = rand () % MSIZE;
r_line = rand () % MSIZE;
printf ("%d %d \n", r_colum, r_line);
map[r_line][r_colum] = 1;
/* Write the map */
for (i = 0; i < MSIZE; i++) {
for (j = 0; j < MSIZE; j++) {
printf ("%d ", map[i][j]);
}
printf ("\n");
}
return 0;
}
示例的/使用/输出强>
$ ./bin/arraymap
2 9
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0