fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef enum {
  5. INT, FLOAT, DOUBLE
  6. } Type;
  7.  
  8. void initMat(Type type, int matSize, void **matA, void **matB, void **matC){
  9. switch(type) {
  10. case INT :
  11. *matA = malloc(matSize * sizeof(int*));
  12. *matB = malloc(matSize * sizeof(int*));
  13. *matC = malloc(matSize * sizeof(int*));
  14. int **matA_i = *matA;
  15. int **matB_i = *matB;
  16. int **matC_i = *matC;
  17.  
  18. for (int i = 0; i < matSize; i++) {
  19. matA_i[i] = malloc(matSize * sizeof(int));
  20. matB_i[i] = malloc(matSize * sizeof(int));
  21. matC_i[i] = malloc(matSize * sizeof(int));
  22. for (int j = 0; j < matSize; j++) {
  23. matA_i[i][j] = rand() % 11;
  24. matB_i[i][j] = rand() % 11;
  25. matC_i[i][j] = 0;
  26. }
  27. }
  28. break;
  29.  
  30. case FLOAT :
  31. case DOUBLE :
  32. //not yet
  33. *matA = NULL; *matB = NULL; *matC = NULL;
  34. break;
  35.  
  36. default :
  37. printf("Invalid case.\n" );
  38. }
  39. }
  40.  
  41. void displayMat(Type type, int matSize, void *matA){
  42. switch(type){
  43. case INT:
  44. {
  45. int **mat = matA;
  46. for(int i = 0; i < matSize; ++i){
  47. for(int j = 0; j < matSize; ++j){
  48. if(j)
  49. putchar(' ');
  50. printf("%d", mat[i][j]);
  51. }
  52. putchar('\n');
  53. }
  54. }
  55. break;
  56. default:
  57. printf("not yet\n");
  58. }
  59. }
  60.  
  61. int main(void){
  62. Type type = INT;
  63. int size = 0;
  64. void *matA, *matB, *matC;
  65.  
  66. int sizes[6] = {3, 4, 5};
  67. int matSize = sizes[size];
  68. printf("The selected matrix size is: %d.\n", matSize);
  69.  
  70. initMat(type, matSize, &matA, &matB, &matC);
  71.  
  72. displayMat(type, matSize, matA);
  73. //deallocate mat
  74.  
  75. }
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
The selected matrix size is: 3.
6 6 1
0 3 8
5 7 9