-1

Basically I am trying to assign a value to a struct through a function,so that the value that I've assigned is the same on main() afterwards.

The struct

struct member{
  char name;
  int age;
}m1;


void assigntostruct(struct member str,int age){

str.age = age;


main(){
int age=10;
assigntostruct(m1,age);
printf("%d",age);

}

I've tried it like this, the value "age" is passed to str.age, but then when I printf it returns 0.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
kostis14
  • 21
  • 3
  • You're missing at least a closing brace for `assigntostruct`. Can you post code that at least compiles? – Stephen Newell Dec 14 '20 at 20:28
  • There is no need to pass `m1` to the function, since it is declared at global scope it is already accessible from `assigntostruct()`, just use `m1.age = age;` and you're done. – David Ranieri Dec 14 '20 at 20:43

1 Answers1

0

You need to pass an object of the structure type by reference.

In C the term passing by reference means passing an object indirectly through a pointer to it.

So the function can look like

void assigntostruct( struct member *str, int age){
    str->age = age;
    //...
}

and can be called like

assigntostruct( &m1, age );
printf("%d", m1.age);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335