Structures in C Programming
Structures in C Programming
struct date
{
int day;
int month;
int year;
};
Note : When you first define a structure in a file, the statement simply tells
the C compiler that a structure exists, but causes no memory allocation. Only
when a structure variable is declared, memory allocation takes place.
Initializing Structures
order_date.day = 9;
order_date.month = 12;
order_date.year = 1995;
Here you have typedefined a unsigned integer as Uint, you can then use Uint
in your program as any native data type, and declare other variables with its
data type. You can similarly typedef a structure too.
Then you can use the newly defined data type, as in the following example:
center_of_circle center1;
center_of_circle center2;
Nested structures
One can define a structure which in turn can contain another structure as one
of its members.
circle c1;
To access a particular member inside the nested structure requires the usage
of the dot notation.
c1.center.x = 10;
This statement sets the x value of the center of the circle to 10.
Arrays of structures
C does not limit a programmer to storing simple data types inside an array.
User defined structures too can be elements of an array.
This defines an array called birthdays that has 10 elements. Each element
inside the array will be of type struct date. Referencing an element in the
array is quite simple.
birthdays[1].month = 09;
birthdays[1].day = 20;
birthdays[1].year = 1965;
There can also be structures containing arrays as its elements. Do not confuse
this concept with array of structures.
struct car{
char name[5];
int model_number;
float price;
};
This sets up a structure with a name car which has an integer member
variable model_number, a float member variable price and a character array
member called name. The character array member has an array of 5
characters.
Just like a variable, you can declare a pointer pointing to a structure and
assign the beginning address of a structure to it. The following piece of code
will help understand this concept.
typedef struct {
int account_num;
char account_type;
char f_name[40];
char l_name[40];
float balance;
} account;
Another important concept one must learn is the usage of the -> operator in
conjunction with a pointer variable pointing to a structure.
Source : http://www.peoi.org/Courses/Coursesen/cprog/frame8.html