fork download
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <stdlib.h>
  4. #include <memory.h>
  5. #include <stdbool.h>
  6. //#include <crtdbg.h>//vc only
  7. typedef struct Hoge {
  8. int32_t* p;
  9. size_t N;
  10.  
  11. int32_t*(*Index)(struct Hoge*, size_t);
  12. bool(*Resize)(struct Hoge*, size_t);
  13. void(*Destruct)(struct Hoge*);
  14. }Hoge;
  15.  
  16. static int32_t* Idx(Hoge* H, size_t N) {
  17. if (H->N <= N) return NULL;
  18.  
  19. return &H->p[N];
  20. }
  21.  
  22. static bool Rsz(Hoge* H, size_t N) {
  23. int32_t *P = NULL;
  24. size_t C = H->N;
  25.  
  26. if (H->N == N)return false;
  27.  
  28. P = calloc(N, sizeof(int32_t));
  29. if (P != NULL) {
  30. if (C > N)C = N;
  31. //memcpy_s(P, N * sizeof(int32_t), H->p, C * sizeof(int32_t));
  32. memcpy(P, H->p, C * sizeof(int32_t));
  33. free(H->p);
  34. H->p = P;
  35. H->N = N;
  36. }
  37. else {
  38. return false;
  39. }
  40. return true;
  41. }
  42. static void DestructHoge(Hoge* H) {
  43.  
  44. free(H->p);
  45. H->p = NULL;
  46. H->N = 0;
  47. return;
  48. }
  49.  
  50. Hoge ConsutructHoge(size_t N) {
  51. Hoge H;
  52. H.Index = Idx;
  53. H.Resize = Rsz;
  54. H.Destruct = DestructHoge;
  55.  
  56. H.p = calloc(N, sizeof(int32_t));
  57. H.N = 0;
  58. if (H.p != NULL) H.N = N;
  59.  
  60. return H;
  61. }
  62.  
  63. int main() {
  64. //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  65. Hoge H = ConsutructHoge(16);
  66.  
  67. (*H.Index(&H, 8)) = 256;
  68.  
  69. for (size_t i = 0; i < H.N; i++) {
  70. printf("%d ", (*H.Index(&H, i)));
  71. }
  72. printf("\n");
  73. H.Resize(&H, 32);
  74. (*H.Index(&H, 7)) = 256;
  75. for (size_t i = 0; i < H.N; i++) {
  76. printf("%d ", (*H.Index(&H, i)));
  77. }
  78. printf("\n");
  79. H.Resize(&H, 8);
  80.  
  81. for (size_t i = 0; i < H.N; i++) {
  82. printf("%d ", (*H.Index(&H, i)));
  83. }
  84. printf("\n");
  85. H.Destruct(&H);
  86.  
  87. return 0;
  88.  
  89. }
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
0 0 0 0 0 0 0 0 256 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 256 256 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 256