EXAMPLE 1
1: /* Demonstrates passing a structure to a function. */
2:
3: #include <stdio.h>
4:
5: /* Declare and define a structure to hold the data. */
6:
7: struct data{
8: float amount;
9: char fname[30];
10: char lname[30];
11: } rec;
12:
13: /* The function prototype. The function has no return value, */
14: /* and it takes a structure of type data as its one argument. */
15:
16: void print_rec(struct data x);
17:
18: main()
19: {
20: /* Input the data from the keyboard. */
21:
22: printf("Enter the donor's first and last names,\n");
23: printf("separated by a space: ");
24: scanf("%s %s", rec.fname, rec.lname);
25:
26: printf("\nEnter the donation amount: ");
27: scanf("%f", &rec.amount);
28:
29: /* Call the display function. */
30: print_rec( rec );
31:
32: return 0;
33: }
34: void print_rec(struct data x)
35: {
36: printf("\nDonor %s %s gave $%.2f.\n", x.fname, x.lname,
37: x.amount);
38: }
EXAMPLE 2
1: /* Example of a typical use of a union */
2:
3: #include <stdio.h>
4:
5: #define CHARACTER `C'
6: #define INTEGER `I'
7: #define FLOAT `F'
8:
9: struct generic_tag{
10: char type;
11: union shared_tag {
12: char c;
13: int i;
14: float f;
15: } shared;
16: };
17:
18: void print_function( struct generic_tag generic );
19:
20: main()
21: {
22: struct generic_tag var;
23:
24: var.type = CHARACTER;
25: var.shared.c = `$';
26: print_function( var );
27:
28: var.type = FLOAT;
29: var.shared.f = (float) 12345.67890;
30: print_function( var );
31:
32: var.type = `x';
33: var.shared.i = 111;
34: print_function( var );
35: return 0;
36: }
37: void print_function( struct generic_tag generic )
38: {
39: printf("\n\nThe generic value is...");
40: switch( generic.type )
41: {
42: case CHARACTER: printf("%c", generic.shared.c);
43: break;
44: case INTEGER: printf("%d", generic.shared.i);
45: break;
46: case FLOAT: printf("%f", generic.shared.f);
47: break;
48: default: printf("an unknown type: %c\n",
49: generic.type);
50: break;
51: }
52: }
EXAMPLE 3
struct student
{
name char[30];
marks float;
}
main ( )
{
struct student student1;
student1 = read_student ( )
print_student( student1);
read_student_p(student1);
print_student (student1);
}
struct student read_student( ) \\ A
{
struct student student2;
gets(student2.name);
scanf("%d",&student2.marks);
return (student2);
}
void print_student (struct student student2) \\ B
{
printf( "name is %s\n", student2.name);
printf( "marks are%d\n", student2.marks);
}
void read_student_p(struct student student2) \\ C
{
gets(student2.name);
scanf("%d",&student2.marks);
}