C Programming Passing Structures To Functions
Last modified by Microchip on 2023/11/09 09:06
If a function requires a structure as a parameter, you will pass it to the function like any ordinary variable. In the code example below, there are two variables: a and b, declared with the type complex. The function display() takes one parameter of type complex. So, you can simply pass either the variable a or b to the function display() as shown in the example.
Example
1 typedef struct
2 {
3 float re;
4 float im;
5 } complex;
6
7 void display(complex x)
8 {
9 printf(“(%f + j%f)\n”, x.re, x.im);
10 }
11
12 int main(void)
13 {
14 complex a = {1.2, 2.5};
15 complex b = {3.7, 4.0};
16
17 display(a);
18 display(b);
19 }
2 {
3 float re;
4 float im;
5 } complex;
6
7 void display(complex x)
8 {
9 printf(“(%f + j%f)\n”, x.re, x.im);
10 }
11
12 int main(void)
13 {
14 complex a = {1.2, 2.5};
15 complex b = {3.7, 4.0};
16
17 display(a);
18 display(b);
19 }