By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,192 Members | 1,276 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,192 IT Pros & Developers. It's quick & easy.

How to get a structure variable in function?

P: n/a
Can I get a structure variable in function
for eg:-
Expand|Select|Wrap|Line Numbers
  1. struct stud{ 
  2.             char name[20]}stud1;
  3.  
  4. void student(char);
  5. void main()
  6. {
  7.     char n[20];
  8.     scanf("%s",n);
  9.     strcpy(stud1.name,n);
  10.     student(stud1.name);
  11. }
  12. void student(char k)
  13. {
  14.    printf(k);
  15. }
Nov 3 '10 #1
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
Do you mean can you pass it to a function? Yes.

The question you need to ask is what is the type of stud1.name. That is nothing to do with structures but rather is a question about arrays.

Once you can answer that question then you just need to give your function parameter that type.

As a clue you already pass stud1.name to another function at line 9. What type does that function use to accept it?
Nov 3 '10 #2

Oralloy
Expert 100+
P: 983
Sajini Biju,

You have several couple choices, depending on what you need to accomplish.

You can pass just the address of the name array:
Expand|Select|Wrap|Line Numbers
  1. void student(char *);
  2. void main()
  3.     char n[20]; 
  4.     scanf("%s",n); 
  5.     strcpy(stud1.name,n); 
  6.     student(stud1.name); 
  7. void student(char *k) 
  8.    printf("%s", k); 
  9. }

You can pass the entire stud structure:
Expand|Select|Wrap|Line Numbers
  1. ...
  2. void student(struct stud);
  3. void main()
  4.     char n[20]; 
  5.     scanf("%s",n); 
  6.     strcpy(stud1.name,n); 
  7.     student(stud1); 
  8. void student(struct stud k) 
  9.    printf("%s", k.name);
  10. }



You can pass a reference to the stud structure:
Expand|Select|Wrap|Line Numbers
  1. ...
  2. void student(struct *stud);
  3. void main()
  4.     char n[20]; 
  5.     scanf("%s",n); 
  6.     strcpy(stud1.name,n); 
  7.     student(&stud1); 
  8. void student(struct stud *k) 
  9.    printf("%s", k->name);
  10. }

Note, too, that I inserted a format in your printf() call. This is to guard against the case where the string to be printed has something that appears as a format specification, which would then result in garbage out.

Luck!
Nov 3 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.