Search code examples
cstringstructcharvoid

How do I add a string to a struct using a function?


I made a parking system where I entered the information of the vehicles using the void function. But I don't know how to put the strings into the struct by using void.

And here is my code. Where is my mistake?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct car {
  char plate[10];
  char model[20];
  char color[10];
};

void main() {

  struct car c[4];

  AddCar(c[0], "43ds43", "ford", "blue");
  ShowCar(c[0]);

  return 0;
}
// I guess my mistake is here
void AddCar(struct car c, char p[10], char m[10], char r[10]) {
  strcpy(c.plate, p);
  strcpy(c.model, m);
  strcpy(c.color, r);
}

void ShowCar(struct car c) {
  printf("Plate: %s   Model: %s  Color: %s\n-------", c.plate, c.model, c.color);
}

Solution

  • There are a number of errors in your code! To address the 'other' ones first:

    1. You need to provide function prototypes for AddCar and ShowCar before you use them, or the compiler will assume they return int and then complain when it sees the actual definitions.
    2. Your main function (properly) returns 0 but it is declared as void - so change it to int main(...).

    And the 'real' problem: you are passing your car structure to AddCar by value - which means a copy is made, then passed to the function. Changes to that copy will not affect the variable in the calling module (i.e. in main). To fix this, you need to pass a pointer to the car struct, and use the -> operator (in place of the . operator) in that function.

    Here's a 'fixed' version of your code, with comments added where I've made significant changes:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct car {
        char plate[10];
        char model[20];
        char color[10];
    };
    
    // Add your functions' prototypes before you use them...
    void AddCar(struct car *c, char p[10], char m[10], char r[10]);
    void ShowCar(struct car c);
    
    int main() // If you return an int, you must declare that you do!
    {
        struct car c[4];
        // Here, we pass a pointer to `c[0]` by adding the `&` (address of)...
        AddCar(&c[0], "43ds43", "ford", "blue");
        ShowCar(c[0]);
        return 0;
    }
    
    void AddCar(struct car *c, char p[10], char m[10], char r[10])
    {                   // ^ To modify a variable, the function needs a POINTER to it!
        strcpy(c->plate, p);
        strcpy(c->model, m);  // For pointers to structures, we can use "->" in place of "."
        strcpy(c->color, r);
    }
    
    void ShowCar(struct car c)
    {
        printf("Plate: %s   Model: %s  Color: %s\n-------", c.plate, c.model, c.color);
    }
    

    Feel free to ask for further clarification and/or explanation.