Implement function
add_recordthat adds a new struct animal record to the dynamic array, and reallocates the array as needed. The start of the dynamic array is given in parameterarray, and the current length of the array is given in parametersize. The new information to be added is given as parameternewanimal. Note that the content ofnewanimalneeds to be copied to the array. Pay attention to which parameters are pointers and which are not. The function returns address to the dynamic array after the addition.
That's my assignment here, can someone explain me why my function add_record is not working ? Anything else here cannot be changed, only the function add_record can be.
My code:
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
// Single animal entry
struct animal {
char id[7]; // animal ID (6 characters) + terminating '\0'
char *name; // animals name
char *species; // animal species (string)
unsigned char age; // animals age
struct date entrydate; // date of the animals arrival
};
struct animal *add_record(struct animal *array, unsigned int size, struct animal newanimal)
{
int n = size + 1;
struct animal *newarray = realloc(array, n*sizeof(struct animal));
array = newarray;
strcpy(array->id, newanimal.id); //copying new id to array
array->name = malloc(strlen(newanimal.name) + 1); //allocating memory for the string
strcpy(array->name, newanimal.name); //copying the new name to array
array->species = malloc(strlen(newanimal.species) + 1); //allocating memory for the string
strcpy(array->species, newanimal.species); //copying the new species to array
array->age = newanimal.age;
array->entrydate = newanimal.entrydate;
return array;
}
int main()
{
/*making new animal zoo which I want to which all of them I need to
add to array in function add_record*/
struct animal zoo[] = {
{ "123456", "Winnie-the-Pooh", "Bear", 94,{ 1,1,1924 } },
{ "555666", "Eeyore", "Donkey", 92,{ 1,1,1926 } },
{ "773466", "Piglet", "Very Small Animal", 30,{ 31, 12, 2015 } },
{ "234567", "Roo", "Kangaroo", 5,{ 31, 12, 2015 } }
};
struct animal *array = NULL;
unsigned int len = 0;
for (unsigned int i = 0; i < sizeof(zoo) / sizeof(struct animal); i++) {
struct animal *newarray = add_record(array, len, zoo[i]);
len++;
array = newarray;
}
return 0;
}