Home C C++ Java Python Perl PHP SQL JavaScript Linux Online Test Forum

C Tutorial on Structure

Structure one of the user defined data type in C programming. A structure can contain similar or different type of data types. We can also create variable of structure like other data types in C.

Short Notes on Structure

  • Structure can contain any data type
  • Size of structure is the sum of its element's sizes
  • Structure can contain pointer to itself
  • Structure can contain another structure
  • We can create array of structure variable

Syntax to declare Structure

struct struct_name
{
	Element1;
	Element2;
};

When we first define a structure, the statement simply tells the Compiler that a structure exist and no memory is allocated for structure till this time. Memory is allocated only when a structure variable is declared.

Declare Structure Variable

struct struct_name
{
	Element1;
	Element2;
};
struct struct_name var1;

Declare Structure Variable Using Typedef keyword

C language allows a programmer to rename any data type using the "typedef" keyword. We can typedef int, char, float and also userdefined data types like enum, structure & union.

typedef struct struct_name
{
	Element1;
	Element2;
}MYSTRUCT;

MYSTRUCT var1;

Initialize Structure's Elements

Unlike normal variables, the syntax of initializing structure variables is quite different. The structure elements are accessed using the dot operator. Look at the below example

Initializing Individual Elements

var1.Element1 = somevalue;
var1.Element2 = somevalue;

Initializing All Elements together

struct var1 = {somevalue, somevalue};

Partial Initializing of Elements - We can also initialize few elements of structure instead of initializing all elements.

struct var1 = {somevalue};

Nested Structures

C programming allows to have nested structures

Array of Structures

We can create array of structure like other data types in C programming. Array of structure can be accessed using index []

Access Structure Elements using Pointer

We can declare pointer to structure and can access all of its elements. The address of structure and it's first element address is same.