[英]Function generates random number in array
I am trying to create a function that creates random number for a array. 我正在尝试创建一个为数组创建随机数的函数。 Here is my code.
这是我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define ROW 22
#define COL 80
void display(int life[ROW][COL]){
for(int i = 0; i<ROW; i++){
for(int j=0; j<COL; j++){
printf("%d",life[i][j]);
}
printf("\n");
}
}
void initialize_board(int life[ROW][COL]){
for(int i = 0; i< ROW;i++){
for(int j = 0; j<COL ; j++){
life[ROW][COL] = rand()%2;
}
}
}
int main() {
srand(getpid());
printf("PID: %d\n",getpid());
int life[22][80] = {0};
initialize_board(life);
display(life);
return 0;
}
However I got output are 0s not randomly assigned to 0 or 1. 但是我得到的输出是0,而不是随机分配给0或1。
Instead of 代替
life[ROW][COL] = rand()%2;
use 采用
life[i][j] = rand()%2;
inside that loop. 在那个循环中。
As it stands, you're writing all random values to the same (invalid) memory address a bit behind the end of the array. 就目前而言,您正在将所有随机值写入同一(无效)内存地址,位于数组末尾。
[ROW][COL
] are constanst, so you're writing always in the same (invalid, as Wintermute mentioned) cell. [ROW][COL
]是常量,因此您总是在同一单元格(无效,如Wintermute所述)中编写内容。 So you had to use the variables i
and j
kind regards 因此,您必须使用变量
i
和j
问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.