Search code examples
cstructstrcpy

initialising structs via function with strcpy in c


I am a beginner in c and am wondering why my function feed_struct doesn't copies the strings I handle to it. This funcion ( feed_struct) should take input data and put it in a struct, which I defined globally. Does anyone know why there happens nothing with the struct? Thanks for your help in advance!

void feed_struct(struct student x, char name [20], char lname [20], double a, char adres [50], int b)
{
    strcpy(x.name, name);
    strcpy(x.lastname, lname);
    x.number = a;
    strcpy(x.adres, adres);
    x.course = b;


}

int main (void)
{
    struct student new_student;
    feed_struct(new_student, "Peter", "Panther", 1230, "El-Lobo-Street 32", 72);
    struct_print(new_student);
    return 0;

}  

Solution

  • You're passing new_student to feed_struct directly by value. So changes in the function are not visible in main.

    You need to pass a pointer to struct student to feed_struct. Then you can dereference that pointer to change the pointed-to object.

    // first parameter is a pointer
    void feed_struct(struct student *x, char name [20], char lname [20], double a, char adres [50], int b)
    {
        strcpy(x->name, name);
        strcpy(x->lastname, lname);
        x->number = a;
        strcpy(x->adres, adres);
        x->course = b;
    
    
    }
    
    int main (void)
    {
        struct student new_student;
        // pass a pointer
        feed_struct(&new_student, "Peter", "Panther", 1230, "El-Lobo-Street 32", 72);
        struct_print(new_student);
        return 0;
    
    }