- 2071 Shrawan · 4 marks
Sending structure members to a function
Short answer
Structure members are passed to functions like ordinary variables: non-array members by value, character arrays by address. e.g., showMarks(s.marks) passes a copy of the float member, while showName(s.name) passes the address of the string.
Write the program "to understand how structure members are sent to a function".
A member of a structure is an ordinary variable, so it can be sent to a function just like any other variable by writing structure_variable.member in the call.
- A member of a basic type (
int,float,char) is sent by value: the function gets a copy, and the original does not change. - A character array member (
s.name) is sent as an array, so its address is passed (the function can change it). - The type of the parameter must match the type of the member.
#include <stdio.h>
struct student {
char name[20];
int roll;
float marks;
};
/* a single member is sent: passed by value */
void showMarks(float m)
{
printf("Marks received in function = %.1f\n", m);
}
/* name member is a character array: its address is sent */
void showName(char n[])
{
printf("Name received in function = %s\n", n);
}
int main(void)
{
struct student s = {"Ram", 10, 78.5};
showMarks(s.marks); /* member sent as argument */
showName(s.name);
showMarks(s.roll); /* int converted to float */
return 0;
}
Output
Marks received in function = 78.5
Name received in function = Ram
Marks received in function = 10.0
s.marks (float) and s.name (char array) were sent to separate functions. In the last call the int member s.roll is converted to float by the compiler.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Structure of a FORTRAN program · Computer Programming, chapter 11 · asked 5×
- Declaration vs definition; C program structure · Computer Programming, chapter 3
- Structure vs array; accessing members · Computer Programming, chapter 8
- Height difference using nested structure · Computer Programming, chapter 8
- College records with nested date structure · Computer Programming, chapter 8
- Complex number multiplication using structure · Computer Programming, chapter 8
- Program using static members · Object Oriented Programming, chapter 4
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3
- Access overridden members from derived class · Object Oriented Programming, chapter 6 · asked 2×
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6