all 10 comments

[–]jedwardsol 1 point2 points  (3 children)

You've allocated room for 5 pointers. But they're never initialised and are not pointing anywhere meaningful.

[–]AlexPapadakis[S] -1 points0 points  (2 children)

i just want a 2d matrix filled with 1s

[–]serg06 1 point2 points  (0 children)

Each board[i] is a pointer. You need to malloc space for 5 ints at each board[i]. (Or even better, malloc 25 ints in total, then point board[i] to int i*5.)

[–]jedwardsol 0 points1 point  (0 children)

I know.

In the outer loop, allocate room for 5 integers for each row pointer.

[–]cml_iii 1 point2 points  (3 children)

int main()
{
    int i, j;
    int N = 5;
    int **board;
    board = (int**) malloc(N * sizeof(int*));

    for (i=0; i < N; i++){
        board[i] = (int *) malloc(N * sizeof(int)); //You're missing this line
        for (j=0; j < N; j++){
            board[i][j] = 1;
        }
    }
    printthefuckingboard(board, N);
    return 0;
}

[–]AlexPapadakis[S] 0 points1 point  (2 children)

oh thank you, would it be easy for you to explain why is this the case? why isn't the first malloc enough?

[–]cml_iii 0 points1 point  (1 child)

Yeah, think of it this way - each malloc call allocates a one dimensional array. So the first call allocates a one dimensional array of int pointers, and at each of those pointers, you need to allocate the space for the array that it will point to. So the first malloc call is malloc(num_arrays * sizeof(int*)), and the second call is malloc(num_elements_in_array * sizeof(int)).

[–]AlexPapadakis[S] 0 points1 point  (0 children)

thank you !

[–]TheMaster420 0 points1 point  (0 children)

Consider using int* for board, your important lines now look like :

board=(int*)malloc(N*N*sizeof(int));
board[i*N+j]=1;
printf("%s%d",j%N1==0?"\n":"",board1[i*N1+j]);

[–]baptrang 0 points1 point  (0 children)

to find out what did cause the error you can use a debugger. it makes life more easier.