Bidimensional数组中的随机数为零

时间:2015-09-15 01:22:00

标签: c arrays for-loop

我正在尝试创建一个零维数组,并在其中生成一个随机数组。但是当我编译它时,它用随机列填充随机列。我看到错误是在循环中写入地图,因为如果我把所有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列,而不是在所有列中。

The 1 is supposed to be on line 16 column 4, not in all columns.

1 个答案:

答案 0 :(得分:1)

最好不要删除可变长度数组,并使用简单的#define(修复后,复制/粘贴错误r_colunar_linha)。尝试:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define MSIZE 20

int main (void)
{
    int map[MSIZE][MSIZE] = Explorer;
    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