Introduction

In C, a structure is a user-defined data type that can be used to group items of possibly different types into a single type.

Syntax

  1. declaration:
struct structure_name
{
	data_type member_1;
	data_type member_2;
	.
	.
	data_type member_n;

} [structure_variables];
  1. Initialization
struct StructureName variableName = {value1, value2, /* ... */};

//Or

struct StructureName variableName = {.member1 = value1, .member2 = value2, /* ... */};

Accessing Member of Structure:

To access struture members we can use dot operator (.) between structure name and structure member name as follows:

**structure_variablename.structure_member** 

Example:

#include <stdio.h>

// Defining a structure to represent a student
struct student
{
	char name [35];
	int age;
	float Percentage;
};

int main()
{

    // Declaring and initializing a structure variable
    struct student s1 = {"Rahul", 20, 18.5};

    printf("%s\\t %d \\t %.2f\\n", s1.name, s1.age, s1.Percentage);
    
    return 0;
}
#include <stdio.h>
#include <string.h>

// Defining a structure to represent a student
struct student
{
	char name [35];
	int age;
	float Percentage;
} s1;

int main()
{

    // Declaring and initializing a structure variable
    
    strcpy(s1.name,"Rahul");
    s1.age = 44;
    s1.Percentage = 22;
    
    printf("%s\\t %d \\t %.2f\\n", s1.name, s1.age, s1.Percentage);
    
    return 0;
}

Array vs Structure

  1. An array is a collection of related data elements            1. A structure can have elements of different types.