Structure in C

Structure is a one concept that used to create our own data type or you can say user define data type. Simply we use the structure to create the user define data type.

Structure size is not fixed. It's depends on number of data types in structure. In structure we can create multiple data types.

Syntax of structure:


    struct struct_name
    {
    data_types variable_name1;
    data_types variable_name2;
    data_types variable_n;
    }struct_variable_name;
    	

How many ways we can create structure variable in C?

In three ways we can create structure variables in C.

Example: structure variable_name declaration inside the terminating semi column.


	struct book
    {
    char bname[20];
    int pages;
    float price;
    }b;

Example: structure variable_name declaration outside the terminating semi column.


    struct book
    {
    char bname[20];
    int pages;
    float price;
    };
    
    struct book b;

Example: structure variable_name declaration inside the main() function.


    struct book
    {
    char bname[20];
    int pages;
    float price;
    };
    
    void main()
    {
    struct book b; //structure variable declaration inside the main() function.
    }

When structure allocate the memory?

When we declare the variable of structure then memory allocated to structure user define data type.

Example of structure program with inside the terminating semi column:


    #include<stdio.h>
    #include<conio.h>

	struct book
	{
		char bname[20];
		int pages;
		float price;
	}b;

	void main()
	{

		clrscr();
		strcpy(b.bname,"Campuslife");
		b.pages=650;
		b.price=500.00;
		printf("Book Name:- %s",b.bname);
		printf("\nBook Pages:- %d",b.pages);
		printf("\nBook Price:- %f",b.price);
	
    	getch();
	}

Ouput:


    Book Name:- Campuslife
    Book Pages:- 650
    Book Price:- 500.0000

Example of structure program with outside the terminating semi column:


	#include<stdio.h>
	#include<conio.h>

	struct book
	{
		char bname[20];
		int pages;
		float price;
	};
	
	struct book b;
	void main()
	{

		clrscr();
		strcpy(b.bname,"Campuslife");
		b.pages=650;
		b.price=500.00;
		printf("Book Name:- %s",b.bname);
		printf("\nBook Pages:- %d",b.pages);
		printf("\nBook Price:- %f",b.price);
	
    	getch();
	}
	

Ouput:


    Book Name:- Campuslife
    Book Pages:- 650
    Book Price:- 500.0000

strcpy() function definition

In above program we used strcpy() function to store the string or character value. Without strcpy() function you cannot store the string or character value.

Post Your Comment