fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct news
  6. {
  7. size_t size;
  8. char *name;
  9. }
  10. news;
  11.  
  12.  
  13. news* insert(news *note, char *text, int i)
  14. {
  15. //NB: if note is NULL realloc acts like malloc
  16. news* new_note=(news*)realloc(note, (i+1)*sizeof(news));
  17. if (new_note)
  18. {
  19. size_t size=strlen(text)*sizeof(char);
  20. new_note[i].size=size;
  21. new_note[i].name = malloc(size +1); //make room for /0
  22. strcpy(new_note[i].name,text); //copies trailing /0 as well
  23. }
  24. return (new_note);
  25. }
  26.  
  27. int main()
  28. {
  29. news *note=NULL;
  30. int j,k;
  31.  
  32. for (j=0;j<5;j++)
  33. {
  34. news* new_note=insert(note,"hello",j);
  35. if (new_note)
  36. {
  37. note=new_note;
  38. printf("%s\n",note[j].name);
  39. }
  40. else //bork
  41. break;
  42. }
  43.  
  44.  
  45. //don't forget to free your allocations !
  46. for (k=0;k<j;k++)
  47. free(note[k].name);
  48. free(note);
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
hello
hello
hello
hello
hello