1

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;

}  
Stokes
  • 13
  • 2

2 Answers2

2

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;

}  
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thanks a lot, it works now!There is one thing I still don't get:`struct student new_student` isn't a pointer, why can you use it as a pointer by passing its adres to feed_struct? – Stokes Dec 26 '18 at 18:10
0

You are passing the struct by value. The strcpy calls copy strings to a local copy of the struct, that's discarded at the end of the function. You should instead pass a pointer to it, so the same struct can be initialized:

void feed_struct(struct student* x, /* pointer to struct student */
                 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;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350