fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4.  
  5. #define ROW_PTR_BLOCK_SIZE(TYPE, ROW_COUNT) ROW_COUNT * sizeof(TYPE *)
  6. #define ROW_BLOCK_SIZE(TYPE, COL_COUNT) COL_COUNT * sizeof(TYPE)
  7. #define BLOCK_SIZE(TYPE, ROW_COUNT, COL_COUNT) ROW_PTR_BLOCK_SIZE(TYPE, ROW_COUNT) + ROW_COUNT * ROW_BLOCK_SIZE(TYPE, COL_COUNT)
  8. #define ALLOCATE(STACK_TOP, TARGET, TYPE, COUNT) do{TARGET = (TYPE *)STACK_TOP; STACK_TOP += COUNT * sizeof(TYPE);}while(0)
  9.  
  10. int func(int a1_row, int a1_col, int a2_row, int a2_col, int a3_row, int a3_col, double ***a1_dst, int ***a2_dst, float ***a3_dst)
  11. {
  12. char *stack[3];
  13. char *stack_top[3];
  14. int stack_size[3] =
  15. {
  16. BLOCK_SIZE(double, a1_row, a1_col),
  17. BLOCK_SIZE(int, a2_row, a2_col),
  18. BLOCK_SIZE(float, a3_row, a3_col)
  19. };
  20.  
  21. double **a1 = NULL;
  22. int **a2 = NULL;
  23. float **a3 = NULL;
  24. int i;
  25. int succeeded = 1;
  26.  
  27. for(i = 0; i < 3 && succeeded; ++i)
  28. {
  29. stack_top[i] = stack[i] = (char *)malloc(stack_size[i]);
  30. if(!stack[i])
  31. succeeded = 0;
  32. }
  33.  
  34. if(!succeeded)
  35. {
  36. for(i = 0; i < 3; ++i)
  37. if(!stack[i])
  38. break;
  39. for(i = i - 1; i >= 0; --i)
  40. free(stack[i]);
  41. return 0;
  42. }
  43.  
  44. ALLOCATE(stack_top[0], a1, double *, a1_row);
  45. for(i = 0; i < a1_row; ++i)
  46. ALLOCATE(stack_top[0], a1[i], double, a1_col);
  47.  
  48. ALLOCATE(stack_top[1], a2, int *, a2_row);
  49. for(i = 0; i < a2_row; ++i)
  50. ALLOCATE(stack_top[1], a2[i], int, a2_col);
  51.  
  52. ALLOCATE(stack_top[2], a3, float *, a3_row);
  53. for(i = 0; i < a3_row; ++i)
  54. ALLOCATE(stack_top[2], a3[i], float, a3_col);
  55.  
  56. assert(stack[0] + stack_size[0] == stack_top[0]);
  57. assert(stack[1] + stack_size[1] == stack_top[1]);
  58. assert(stack[2] + stack_size[2] == stack_top[2]);
  59.  
  60. *a1_dst = a1;
  61. *a2_dst = a2;
  62. *a3_dst = a3;
  63.  
  64. return 1;
  65. }
  66.  
  67. #define A1_ROW (300)
  68. #define A1_COL (200)
  69. #define A2_ROW (400)
  70. #define A2_COL (300)
  71. #define A3_ROW (500)
  72. #define A3_COL (400)
  73.  
  74. int main(void)
  75. {
  76. double **a1 = NULL;
  77. int **a2 = NULL;
  78. float **a3 = NULL;
  79. int result = func(A1_ROW, A1_COL, A2_ROW, A2_COL, A3_ROW, A3_COL, &a1, &a2, &a3);
  80.  
  81. printf("result = %d\n", result);
  82.  
  83. if(result)
  84. {
  85. free(a1);
  86. free(a2);
  87. free(a3);
  88. }
  89.  
  90. return 0;
  91. }
Success #stdin #stdout 0.01s 1676KB
stdin
Standard input is empty
stdout
result = 1