I am trying to write a C program that ask a user for a number 'n' of cars that he/she wish to catalog and then dynamically create an array of that number of cars. Each element of the array is a variable of type 'car'. the structure 'car' has two members variables:1) make(which is a string that represent the make of the car) and 2) year(an integer representing the year of manufacture of the car). What I want is my program to read the make and the year for each element of the array stated above. At the end I will print each element of that array. My code is below. But this code cannot read the make and the year for the car stored in the array.`
#include<stdlib.h>
#include<stdio.h>
struct car {
char *make;
int year;
};
typedef struct car Car;
char *getname()
{
char *str, c;
int i = 0, j = 1;
str = (char *)malloc(sizeof(char));
printf("Enter the make: ");
while (c != '\n') {
// read the input from keyboard standard input
c = getc(stdin);
// re-allocate (resize) memory for character read to be stored
str = (char *)realloc(str, j * sizeof(char));
// store read character by making pointer point to c
str[i] = c;
i++;
j++;
}
str[i] = '\0'; // at the end append null character to mark end of string
return str;
free(str) // important step the pointer declared must be made free
}
int main(void)
{
int i, j, n;
printf("How many cars do you wish to catalog? :");
scanf("%d", &n);
Car *vti; //a pointer so that I will use to store n cars //
vti = (Car *) malloc(n * sizeof(Car));
for (i = 0; i < n; i++) {
printf("Car #%d", i);
vti[i].*(make) = getname();
printf("Enter the year made:");
scanf("%d", &(vti[i].year));
}
for (i = 0; i < n; i++) {
printf("Here is your collection\n");
printf("%s%d\n", vti[i].make, vti[i].year);
}
return 0;
}