C Structure and Function

Let’s move to a more interesting topic: function with structure. Before starting, let’s go back and revise the concept of passing values in function.

void func(int number){ // here that same passed num is received as number 

    //Do whatever you like with number

}

void main(){

    int num = 5;

    func (num); //an integer variable num is passed to function func()

}

If that’s clear to you, let’s pass a structure variable to a function. 

1.Pass structure to a function by value

Here I have a variable named num1 of type complex. What I did, I just passed num1 in the function func(). The function then received the value as complex num. Isn’t it that simple?

2.Return structure from a function

Here the func() return type is not void but complex (Line 8) as the function returns a complex variable num (Line 12)

The returned value is received by modified_num (another complex variable) at Line 19 and printed at Line 20

3.Pass structure to a function by reference

So first remember what you need to do for passing a value by reference

  1. Pass the address of the variable (here &num1 at line 17).
  2. Receive the address as a pointer (don’t forget about correct data type) in the function definition (here complex* num at line 8)

So that’s what is done in the code. And just remember one other thing: to access structure members with a pointer, you need to use operator (Line 10 and 11).

I hope this explains clearly. That’s all.

If you are looking for a book for C programming, please check out the Programming In Ansi C. That is one of my favorites.

Thank you!