Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define MAX_NAME_SIZE 30
- #define INITIAL_STRUCT_SIZE 3
- /* declaration of a stucture */
- typedef struct {
- int age;
- float weight;
- char name[MAX_NAME_SIZE];
- } Persons;
- /* fonction that adds a new person */
- void addPerson(Persons *ptr, int *counter) {
- int incrementer = 0; /* Moves to next position in memory to prevent data overwriting */
- /* while there is enought of memory in ptr, we user `incrementer = (*counter)`, in other cases we call fonction to expand memory */
- if (ptr == NULL)
- expandStruct(&ptr, &counter); /* calling fonction to realloc memory and affecting result to `incrementer` variable */
- printf("Counter : %d\n", *counter);
- /* adding data to structure */
- printf("Enter age, weight and name of the person respectively:\n");
- scanf("%d%*c", &(ptr+*counter)->age);
- scanf("%f%*c", &(ptr+*counter)->weight);
- scanf("%s%*c", &(ptr+*counter)->name);
- (*counter)++; /* incrementing coutner after each new data */
- //printf("Counter = %d\n", *counter);
- //printf("Incrementer = %d\n", incrementer);
- }
- /* dipplaying data */
- void displayPerson(Persons *ptr, int *counter) {
- int i = 0;
- int j = 0;
- j = (*counter);
- i = 0;
- if (j == 0) {
- printf("Currently there is no records\n");
- return;
- }
- printf("Displaying Infromation:\n");
- do {
- printf("%d\t%.2f\t%s\n", (ptr+i)->age, (ptr+i)->weight, (ptr+i)->name);
- i++;
- } while (i < j);
- }
- /* expanding memory if needed */
- void expandStruct(Persons **ptr, int **counter)
- {
- (*counter)++;
- *ptr = realloc(*ptr, sizeof(Persons));
- if(*ptr == NULL)
- {
- printf("Cannot allocate more memory\n");
- exit(EXIT_FAILURE);
- }
- }
- int main(int argc, char * argv[])
- {
- Persons *ptr = NULL;
- int counter = 0;
- int input = 0;
- /* initial memory allocating */
- ptr = (Persons*) malloc(INITIAL_STRUCT_SIZE * sizeof(Persons));
- if (ptr == NULL) {
- printf("Allocation memory fail\n");
- exit(EXIT_FAILURE);
- }
- do {
- printf("1. Add Person\n");
- printf("2. Display Persons\n");
- scanf("%d%*c", &input);
- switch (input) {
- case 1:
- addPerson(ptr, &counter);
- break;
- case 2:
- displayPerson(ptr, &counter);
- break;
- case -1:
- break;
- default:
- printf("Wrong input\n");
- break;
- }
- } while (input != -1);
- return 0;
- }
Add Comment
Please, Sign In to add comment