Structure Definition

A structured data type is a compound data type which falls under user-defined category and used for grouping simple data types or other compound data types. This contains a sequence of member variable names along with their type/attributes and they are enclosed within curl brackets.

Need for Struct data types

There are some situations when we need to group different types of variables in one group. Let's see one situation here- we want to store the name, roll and age of a student.

unsigned int student_roll;
char student_name [MAX_STRING];
unsigned int student_age;
Here we have a logical grouping between there three variables but still these three variables are scattered. We are accessing three different variables for storing attribute values of a single student. Now how to group this inside one logical entity, like three variables for a single student grouped inside one variable. This type of grouping is called structure. One point to note here is that array can group only same type elements and here structure has different types.

Example of Struct data types

Let's define these again with a structure type

struct student_t {
  unsigned int roll;
  char name[MAX_STRING];
  unsigned int age;
};
struct student_t student1;
student1.roll = <roll value>;
strcpy (student1.name, <name>);
10  student1.age = <age>

Structure size and memory layout

Structure is user defined type to group of different type of variables of either compiler defined legacy types or other user defined types or mixed. Individual entity of a structure element is called member. Members inside a structure are placed sequentially next to next in the memory layout. Thus minimum size of a structure is the sum total of all sizes of members, with considering padding.

structure in C

Struct data types syntax

struct <name> {
  <type> <member name 1>;
  <type> <member name 2>;
  ...
  <type> <member name N>;
};

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

Pascals triangle, user defined types, typedef, struct type, union type, struct vs union, struct pack padding, size of a structure,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan