fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5.  
  6. int main(int argc, char * argv[])
  7. {
  8. int ** arr = NULL;
  9. char * endptr = NULL;
  10. long int arr_size = 0;
  11. long int ints_inside_arr = 0;
  12. if (3 != argc)
  13. {
  14. printf("Please Specify the size of the multi dimensional array you want to create and try again!\n");
  15. printf("Example : ./main 3 4\n This would result in a 3x4 multi dimensional array");
  16. exit(0);
  17. }
  18.  
  19. arr_size = strtol(argv[1], &endptr, 10);
  20.  
  21. if (endptr == argv[1])
  22. {
  23. printf("No Digits Were Found!\n");
  24. exit(0);
  25. }
  26. else if (*endptr != '\0')
  27. {
  28. printf("Invalid Character. Please enter digits only in the format of [num] [num2]\n");
  29. exit(0);
  30. }
  31.  
  32. endptr = NULL;
  33.  
  34. ints_inside_arr = strtol(argv[2], &endptr, 10);
  35.  
  36. if (endptr == argv[2])
  37. {
  38. printf("No Digits Were Found!\n");
  39. exit(0);
  40. }
  41. else if (*endptr != '\0')
  42. {
  43. printf("Invalid Character. Please enter digits only in the format of [num] [num2]\n");
  44. exit(0);
  45. }
  46.  
  47. arr = calloc(arr_size, sizeof(int *));
  48.  
  49. if (NULL == arr)
  50. {
  51. perror("Error Allocating Memory For Array!\n");
  52. exit(EXIT_FAILURE);
  53. }
  54.  
  55. for (int i = 0; i < arr_size; i++)
  56. {
  57. arr[i] = calloc(ints_inside_arr, sizeof(int));
  58.  
  59. if (NULL == arr[i])
  60. {
  61. perror("Failure to allocate memory for inner array!\n");
  62. for (int j = 0; j < i; j++)
  63. {
  64. free(arr[j]);
  65. }
  66. free(arr);
  67. exit(EXIT_FAILURE);
  68. }
  69. }
  70. printf("ARRAY OF INTS CREATED : \n");
  71. for (int i = 0; i < arr_size; i++)
  72. {
  73. for (int j = 0; j < ints_inside_arr; j++)
  74. {
  75. arr[i][j] = j;
  76. printf("%d ", arr[i][j]);
  77. }
  78. printf("\n");
  79. }
  80.  
  81. for (int i = 0; i < arr_size; i++)
  82. {
  83. free(arr[i]);
  84. }
  85.  
  86. free(arr);
  87.  
  88. printf("All Memory Successfully Freed!\n");
  89.  
  90. return 0;
  91. }
  92.  
Success #stdin #stdout 0.01s 5320KB
stdin
./main 3 4
stdout
Please Specify the size of the multi dimensional array you want to create and try again!
Example : ./main 3 4
 This would result in a 3x4 multi dimensional array