Search code examples
cpointersstructmallocrealloc

How use index in a pointer with Struct and pointer in C


I need to make a program that can register some car. Then I need show all the cars registeres.

I can't make this work, when I execute the code below the printf show just memory trash, and just the last car appears right!

Code (I have a menu function that call the others):

int id = 0;

struct car {

    char brand[50];
    char model[50];

};
car *garage = 0;
int doCar(){

    garage = (struct car *)malloc(sizeof(struct car*));
    printf("\n Insert the model: \n\n");
    fflush(stdin);
    fgets( garage[id].model, 50, stdin);
    id++;

}

int ShowCars(){

    int i = 0;

    while (i < id) {

        printf("aqi= %s \n", garage[id].model);
        i++;

    }   

}

Solution

  • Consider the following example:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct car {
    
        char brand[50];
        char model[50];
    
    };
    
    // dlobal variables
    car* garage = NULL;
    int cnt = 0;
    
    void doCar(){
        // add counter
        cnt++;
        // add memory 
        garage = realloc(garage, sizeof(car) * cnt); // NOTE: not malloc
        printf("Enter the brand: ");
        scanf("%49s", garage[cnt - 1].brand); // or fgets
        printf("Enter the model: ");
        scanf("%49s", garage[cnt - 1].model); // or fgets
    }
    
    void ShowCars(){
        int i;
        for(i = 0; i < cnt; i++)
        {
            printf("%s %s\n", garage[i].brand,  garage[i].model);
        }
    }
    

    EDIT:

    Add the main function to test:

    int main(int argc, char* argv[])
    {
        // test for three cars
        doCar();
        doCar();
        doCar();
        ShowCars();
    
        // free memory after using
        free(garage);
        return 0;
    }