fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. //The related variables are treated together in the structure. and Avoid using global variables.
  6. typedef struct {
  7. int entries;
  8. int mem_allocated;
  9. char **data;
  10. } Entry;
  11.  
  12. void add_Entry(const char *p, Entry *dp);
  13.  
  14. int main(void) {
  15. const char *p0 = "ksdfahj93qhf9";
  16. const char *p1 = "siodfnrieopq";
  17. const char *p2 = "erf9ih94gri9g";
  18.  
  19. Entry dp = { 0 };//initialize
  20.  
  21. add_Entry(p0, &dp);
  22. add_Entry(p1, &dp);
  23. add_Entry(p2, &dp);
  24.  
  25. for(int i = 0; i < dp.entries; i++) {
  26. printf("%s\n", dp.data[i]);
  27. free(dp.data[i]);
  28. }
  29. free(dp.data);
  30. }
  31. void add_Entry(const char *p, Entry *dp){
  32. if(dp->entries == dp->mem_allocated)
  33. dp->mem_allocated += 3;
  34.  
  35. void *temp = realloc(dp->data, dp->mem_allocated * sizeof(*dp->data));
  36. if(!temp){
  37. perror("Memory allocation failed!");
  38. exit(EXIT_FAILURE);
  39. }
  40. dp->data = temp;
  41.  
  42. temp = malloc(strlen(p)+1);
  43. if(!temp){
  44. perror("Memory allocation failed!");
  45. exit(EXIT_FAILURE);
  46. }
  47. dp->data[dp->entries++] = strcpy(temp, p);
  48. }
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
ksdfahj93qhf9
siodfnrieopq
erf9ih94gri9g