Structures in C | C programming

In C, structures is a user defined datatype. It is used to create a group of items of different datatypes into a single type.

Defining a Structure

We use ‘struct’ keyword create a structure which defines a new datatype having more than one member.

Syntax:

struct [structure tag] {

   member definition;
   member definition;
   ...
   member definition;
} [one or more structure variables];  

Example:

struct address {
char name/building.no,[50];
char street[80];
char city[30];
char state[20];
int pin_id;
}

Accessing Structure Members

We use the dot operator (.) to access members of a structure.

#include<stdio.h> 
struct Point
{
int a, b;
}; 
int main()
{
struct Point p1 = {0, 1}; // Accessing members of point p1
p1.a = 20;
printf ("a = %d, b = %d", p1.a, p1.b);

 return 0;
}

Output:

a = 20,  b = 1

Array of structures

We can create an array of structures just like other primitive data types.

#include<stdio.h> 
struct Point
{
int a, b;
}; 
int main()
{
// Create an array of structures
struct Point arr[10]; 
// Access array members
arr[0].a = 20;
arr[0].b = 30; 

printf("%d %d", arr[0].a, arr[0].b);
return 0;
}

Output:

20 30

Structures as Function Arguments

We can pass a structure as a function argument similar to the way any other variable or pointer is passed.

#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);
}

Output

Enter name: Saakshi
Enter age: 20

Displaying information
Name: Saakshi
Age: 20 

Struct variable s1 of type struct student is created. The s1 variable is passed to the display() function.

We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!👋
Can we help you?