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
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.
} [one or more structure variables];
} 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;
struct Date dob;
Using a Structure:
The members of a structure are usually processed individually as separate entities
- variable refers to the name of the struct type variable.
- member1 refers to the name of the member within the structure.
struct Person p1,p2;
printf("Enter Name: ");
printf("Enter Age: ");
printf("Enter Address: ");
printf("Enter date of birth(dd mm yyyy)");
printf("%s of age %d stays at following address\n%s",p1.name,p1.age,p1.address);
printf("Date of birth: %d/%d/%d",p1.dob.Day,p1.dob.Month,p1.dob.Year);
|typedef struct Person
struct Date dob;
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.