/    /  Structure Initialization

Structure Initialization

 

Like primary variables and tables, structure variables can also be initialized at their declared location.

 

The Syntax for structure variable initialization:

 

struct structurename varname={list of values);

 

here the values should be assigned in the same order of declaration of the members in the definition.

 

Example:

 

struct book
{
char name[10] ;
float price ;
int pages ;
} ;
struct book b1 = {"Maths", 100.00, 532};
struct book b2 = {"Physics", 130.80, 682};

 

Examples:

 

1. Define a structure by name student which includes student name,roll number and marks.

 

struct student
{
char name[10];
int rno;
float marks ;
} ;

 

The statement sets a new data type known as struct student.

 

2. Define a structure by name book which includes the name of the book,price, and a number of pages.

 

struct book
{
char name;
float price;
int pages ;
} ;

 

The statement sets a new data type known as struct book.

 

Memory allocation for structure:

 

Whatever the elements of a structure are, they are always stored as contiguous memory.The following program would illustrate this:

 

/* Memory map of structure elements */

 

#include<stdio.h>
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1 = {'B', 130.00, 550};
printf ("\nAddress of name = %u", &b1.name);
printf ("\nAddress of price = %u", &b1.price);
printf ("\nAddress of pages = %u", &b1.pages);
}

 

Output:

 

Structure Initialization

 

In fact, the structure elements are stored in memory as:

 

Structure Initialization