x

C – Passing struct to function

Prev     Next

  • A structure can be passed to any function from main function or from any sub function.
  • Structure definition will be available within the function only.
  • It won’t be available to other functions unless it is passed to those functions by value or by address(reference).
  • Else, we have to declare structure variable as global variable. That means, structure variable should be declared outside the main function. So, this structure will be visible to all the functions in a C program.

Passing structure to function in C:

It can be done in below 3 ways.


  1. Passing structure to a function by value
  2. Passing structure to a function by address(reference)
  3. No need to pass a structure – Declare structure variable as global

Example program – passing structure to function in C by value:

In this program, the whole structure is passed to another function by value. It means the whole structure is passed to another function with all members and their values. So, this structure can be accessed from called function. This concept is very useful while writing very big programs in C.

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000

Example program – Passing structure to function in C by address:

In this program, the whole structure is passed to another function by address. It means only the address of the structure is passed to another function. The whole structure is not passed to another function with all members and their values. So, this structure can be accessed from called function by its address.


Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000

Example program to declare a structure variable as global in C:

Structure variables also can be declared as global variables as we declare other variables in C. So, When a structure variable is declared as global, then it is visible to all the functions in a program. In this scenario, we don’t need to pass the structure to any function separately.

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000

Continue on C – Structure using Pointer….

Continue on C – Structure within Structure….

Continue on C – Structure Memory Allocation….

Continue on C – Structure Padding….

Prev     Next



Like it? Please Spread the word!