Guest User

Untitled

a guest
Nov 17th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define MAX_NAME_SIZE 30
  5. #define INITIAL_STRUCT_SIZE 3
  6.  
  7. /* declaration of a stucture */
  8. typedef struct {
  9. int age;
  10. float weight;
  11. char name[MAX_NAME_SIZE];
  12. } Persons;
  13.  
  14. /* fonction that adds a new person */
  15. void addPerson(Persons *ptr, int *counter) {
  16. int incrementer = 0; /* Moves to next position in memory to prevent data overwriting */
  17.  
  18. /* while there is enought of memory in ptr, we user `incrementer = (*counter)`, in other cases we call fonction to expand memory */
  19.  
  20. if (ptr == NULL)
  21. expandStruct(&ptr, &counter); /* calling fonction to realloc memory and affecting result to `incrementer` variable */
  22.  
  23. printf("Counter : %d\n", *counter);
  24.  
  25. /* adding data to structure */
  26. printf("Enter age, weight and name of the person respectively:\n");
  27. scanf("%d%*c", &(ptr+*counter)->age);
  28. scanf("%f%*c", &(ptr+*counter)->weight);
  29. scanf("%s%*c", &(ptr+*counter)->name);
  30. (*counter)++; /* incrementing coutner after each new data */
  31. //printf("Counter = %d\n", *counter);
  32. //printf("Incrementer = %d\n", incrementer);
  33. }
  34.  
  35. /* dipplaying data */
  36. void displayPerson(Persons *ptr, int *counter) {
  37. int i = 0;
  38. int j = 0;
  39.  
  40. j = (*counter);
  41. i = 0;
  42.  
  43. if (j == 0) {
  44. printf("Currently there is no records\n");
  45. return;
  46. }
  47.  
  48. printf("Displaying Infromation:\n");
  49.  
  50. do {
  51. printf("%d\t%.2f\t%s\n", (ptr+i)->age, (ptr+i)->weight, (ptr+i)->name);
  52. i++;
  53. } while (i < j);
  54. }
  55.  
  56. /* expanding memory if needed */
  57. void expandStruct(Persons **ptr, int **counter)
  58. {
  59. (*counter)++;
  60. *ptr = realloc(*ptr, sizeof(Persons));
  61.  
  62. if(*ptr == NULL)
  63. {
  64. printf("Cannot allocate more memory\n");
  65. exit(EXIT_FAILURE);
  66. }
  67. }
  68.  
  69. int main(int argc, char * argv[])
  70. {
  71. Persons *ptr = NULL;
  72. int counter = 0;
  73. int input = 0;
  74.  
  75. /* initial memory allocating */
  76. ptr = (Persons*) malloc(INITIAL_STRUCT_SIZE * sizeof(Persons));
  77.  
  78. if (ptr == NULL) {
  79. printf("Allocation memory fail\n");
  80. exit(EXIT_FAILURE);
  81. }
  82.  
  83. do {
  84. printf("1. Add Person\n");
  85. printf("2. Display Persons\n");
  86. scanf("%d%*c", &input);
  87.  
  88. switch (input) {
  89. case 1:
  90. addPerson(ptr, &counter);
  91. break;
  92. case 2:
  93. displayPerson(ptr, &counter);
  94. break;
  95. case -1:
  96. break;
  97. default:
  98. printf("Wrong input\n");
  99. break;
  100. }
  101. } while (input != -1);
  102.  
  103. return 0;
  104. }
Add Comment
Please, Sign In to add comment