fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define BUFFSIZE 3 /* >= 2, e.g. 1024 */
  6. char *mygetline(FILE *fp) {
  7. static char inbuff[BUFFSIZE];
  8. char *outbuff_malloc, *tmpbuff;
  9. char *p, *r;
  10. int fEOL;
  11.  
  12. if ((outbuff_malloc = malloc(1)) == NULL) {
  13. return NULL;
  14. }
  15. *outbuff_malloc = '\0';
  16. fEOL = 0;
  17. do {
  18. r = fgets(inbuff, BUFFSIZE, fp);
  19. if (r == NULL)
  20. break;
  21. for (p = inbuff; *p != '\0'; p++)
  22. ;
  23. if (*(p - 1) == '\n')
  24. fEOL = 1;
  25. if ((tmpbuff = realloc(outbuff_malloc, strlen(outbuff_malloc) + strlen(inbuff) + 1)) == NULL) {
  26. free(outbuff_malloc);
  27. return NULL;
  28. }
  29. strcat(tmpbuff, inbuff);
  30. outbuff_malloc = tmpbuff;
  31. } while (!fEOL);
  32. if (strlen(outbuff_malloc) > 0) {
  33. char c;
  34. for (p = outbuff_malloc; *p != '\0'; p++)
  35. ;
  36. while ((c = *(--p)) == '\n' || c == '\r')
  37. *p = '\0';
  38. return outbuff_malloc;
  39. }
  40. free(outbuff_malloc);
  41. return NULL;
  42. }
  43.  
  44. struct vector {
  45. int *array;
  46. int n;
  47. };
  48.  
  49. void init_vector(struct vector *a) {
  50. a->array = 0;
  51. a->n = 0;
  52. }
  53.  
  54. void release_vector(struct vector *a) {
  55. free(a->array);
  56. a->n = 0;
  57. }
  58.  
  59.  
  60. void set_vector(struct vector *a, int i, int v) {
  61. int *new_array;
  62. if (a->n <= i) {
  63. new_array = malloc(sizeof(int) * (i + 1));
  64. if (a->array != 0) {
  65. memcpy(new_array, a->array, sizeof(int) * a->n);
  66. free(a->array);
  67. }
  68. a->array = new_array;
  69. a->n = i + 1;
  70. }
  71. a->array[i] = v;
  72. }
  73.  
  74. int get_vector(struct vector *a, int i) {
  75. if (i < a->n)
  76. return a->array[i];
  77. return 0;
  78. }
  79.  
  80. int main() {
  81. char *p, *nextp;
  82. struct vector a; init_vector(&a);
  83.  
  84. int tmp_value;
  85. int n = 0;
  86.  
  87. while ((p = mygetline(stdin)) != 0) {
  88. printf("<%s>\n", p);
  89. do {
  90. tmp_value = strtol(p, &nextp, 10);
  91. printf("n = %d, tmp_value = %d\n", n, tmp_value);
  92. set_vector(&a, n++, tmp_value);
  93. p = nextp;
  94. } while(*p != 0);
  95. }
  96. for (int i = 0; i < n; i++)
  97. printf("%d: %d\n", i, get_vector(&a, i));
  98.  
  99. release_vector(&a);
  100. free(p);
  101. return 0;
  102. }
  103. /* end */
  104.  
Success #stdin #stdout 0s 9424KB
stdin
123 456 789 1024
stdout
<123 456 789 1024>
n = 0, tmp_value = 123
n = 1, tmp_value = 456
n = 2, tmp_value = 789
n = 3, tmp_value = 1024
0: 123
1: 456
2: 789
3: 1024