0

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++;

    }   

}

2 Answers2

0

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;
}
VolAnd
  • 6,367
  • 3
  • 25
  • 43
  • I don't know why but if i use the printf in the **doCar** function, works fine, but when i try to call the **ShowCars** Function, dont show notting – Junior Barros Apr 27 '15 at 15:17
0

In the function ShowCars, the line printf("aqi= %s \n", (*garage + id).model); you're dereferencing garage and adding id to that struct, which shouldn't make sense. You're better off replacing that with the garage[i] notation that you had earlier, so like this:

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

Also, as someone else mentioned before, you need to allocate a new car of sizeof(struct car) (which would be 50 + 50 = 100) and NOT sizeof(struct car *) (which is most likely on your system 4 for a 32-bit pointer size). Lastly, each time you create a new car, you'll have to increment garage to point to these allocations. Good luck!

reservoirman
  • 119
  • 1
  • 11