0

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Akrios Be more polite to people, including yourself.
Rest assured that there's not one among us who hasn't made similar mistakes before. Except those who are just starting out and haven't written any code yet; they will make them in the future. :P
0

[ROW][COL] are constanst, so you're writing always in the same (invalid, as Wintermute mentioned) cell. So you had to use the variables i and j kind regards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.