fork download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. int main()
  5. {
  6. int rows = 5, cols = 5;
  7.  
  8. int ** board = (int **)malloc(rows * sizeof(int*)); //pointer to a table of pointers
  9. //*board points to an array which stores addresses of the first column of each row
  10. //board[0] = first row
  11. //board[1] = second row
  12. //board[0][0] = first column of first row
  13. //board[2][3] = 4th column of 3rd row
  14.  
  15. board[0] = (int *)malloc(rows * cols * sizeof(int*)); //allocate memory for the whole board in one shot
  16.  
  17. for(int i = 1; i < rows; i++)
  18. board[i] = *board + cols*i; //set the table of pointers
  19.  
  20. //testing code
  21. //fill the first row with multiples of 1 (0, 1, 2, 3, 4)
  22. //fill the second row with multiples of 2 (0, 2, 4, 6, 8)
  23. //.
  24. //.
  25. //.
  26. for(int i = 0; i < rows; i++)
  27. for(int j = 0; j < cols; j++)
  28. board[i][j] = (i+1)*j;
  29.  
  30. //printfs to check if the code is correct
  31. for(int i = 0; i < rows; i++)
  32. {
  33. for(int j = 0; j < cols; j++)
  34. printf("%d ", board[i][j]);
  35. printf("\n");
  36. }
  37. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
0 0 0 0 0 
0 1 2 3 4 
0 2 4 6 8 
0 3 6 9 12 
0 4 8 12 16