Structures and Functions in C

Structures and functions in C programming; Through this tutorial, you will learn how to pass struct variables as arguments to a function. And as well as learn how to return struct from a function with the help of examples.

Structures and Functions

  • Passing Structure Members To Functions in C Program
  • Passing The Entire Structure To Functions in C Program

Passing Structure Members To Functions in C Program

See the following c program to pass structures to a function; as shown below:

#include <stdio.h>
struct student {
   char name[50];
   int age;
};

// function prototype
void display(struct student s);

int main() {
   struct student s1;

   printf("Enter name: ");

   // read string input from the user until \n is entered
   // \n is discarded
   scanf("%[^\n]%*c", s1.name);

   printf("Enter age: ");
   scanf("%d", &s1.age);

   display(s1); // passing struct as an argument

   return 0;
}

void display(struct student s) {
   printf("\nDisplaying information\n");
   printf("Name: %s", s.name);
   printf("\nAge: %d", s.age);
}

Passing The Entire Structure To Functions in C Program

See the following c program to pass entire structures to a functions; as shown below:

#include <stdio.h>
//structures declaration
typedef struct {
    int a, b;
    int c;
}sum;
void add(sum) ;     //function declaration with struct type sum
int main()
{
sum s1;
printf("Enter the value of a : ");
scanf("%d",&s1.a);
printf("\nEnter the value of b : ");
scanf("%d",&s1.b);
add(s1);     //passing entire structure as an argument to function
return 0;
}
//Function Definition
void add(sum s)
{
int sum1;
sum1 = s.a + s.b;
printf("\nThe sum of two values are :%d ", sum1);
}

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to Structures and Functions in C

  1. Wo its amazing to get your website. Thanks for sharing.

Leave a Reply

Your email address will not be published. Required fields are marked *