Structures

Overview of Structures:

Structure is a user defined data type, which contains individual element that can be different in type. Hence structure can contain integer, char, float, double, etc., elements. Arrays, pointer and other structures can be included in structures.
Structures are used to represent a record, Suppose you want to keep track of Student in a class. You might want to track the following attributes about each Student

  • RollNo
  • Name
  • Standard
  • TotalMarks

Note: Individual elements are referred to as members

Defining a Structure:
A structure being complicated than array should be defined in terms of its individual members.

struct <name>
{
member1 definition;
member2 definition;

member definition;
} [one or more structure variables];
struct Student
{
int RollNo;
char Name[30];
int Standard;
double TotalMarks;
} stud1, stud2;
  • Struct is a keyword, is the name that identifies the structure of this type.
  • member1, member2…etc; are individual member declarations.
  • The individual members can be ordinary variables, arrays, points or other structures.
  • The member names within a structure should be distinguished from one another.
  • A member name can be the same as the name of variable that is defined outside the structure.
  • Once the composition of the structure has been defined individual structure type variables are declared as

struct var1, var2, …varn;

eg:

struct Date
{
int Day;
int Month;
int Year;
};
struct Person
{
char name[30];
int age;
char address[50];
struct Date dob;
};

Using a Structure:
The members of a structure are usually processed individually as separate entities
variable.member1

  • variable refers to the name of the struct type variable.
  • member1 refers to the name of the member within the structure.
typedef struct Person
{
char name[30];
int age;
char address[50];
struct Date dob;
} PERSON;
PERSON p1,p2;

typedef vs #define

  • The typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, like you can define 1 as ONE etc.
  • The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor.