- A structure is a user defined composite data type in C.
- A structure is used to group items of possibly different types into a single type.
- Unlike Java/C++ classes, structures do not have member functions.
struct tag_name {
T1 member1;
T2 member2;
/* declare as many members as desired,
but the entire structure size must be
known to the compiler. */
};Example 1: Point with x and y coordinates
- A point has two coordinates
xandy. - In C we can create a new data-type
Pointas
struct Point
{
int x, y
};
int main()
{
struct Point p1; // p1 is an object of type Point
}- There is a shortcut of
struct Point p1i.e., addtypedefbeforestruct. - Structure members are accessed using the dot
(.)operator.
typedef struct Point
{
int x, y
} Point;
int main()
{
Point p1; // p1 is an object of type Point
// for p1(2,3)
p1.x = 2;
p1.y = 3;
}Pointer to a structure object
- We can create pointers to point to structure objects.
- If we have a pointer to structure, members are accessed using arrow
(->)operator.s->xis a shortcut for(*s).x. - Example : Lists
tyepdef struct list_t
{
int elem;
struct list *next;
} list_t;
list_t *myList;
myList = malloc(sizeof(list_t));
myList->elem = 4;
myList->next = NULL;