C Structures

A structure is a group of heterogeneous data elements grouped together under one name. These data elements are called members and they can have different types and different lengths.

Structures enable us to define user-defined data types. 

Syntax for declaring structures  in C is:

struct type_name
{
    member_type1 member_name1;
    member_type2 member_name2;
    member_type3 member_name3;
    .
    .
} object_names;

Here, type_name is a name for the structure type.

Within braces {}, there is a list with the data members, each one is specified with a type and a valid identifier as its name.

object_name can be a set of valid identifiers for objects that have the type of this structure.

 

Example:
struct vehicle {
  char* make;
  int year;
} car, truck;

This declares a structure type, called vehicle. It has two two members: make and year, each of a different fundamental type. Now, vehicle type can be used just like any other type.

Then two objects ( variables): car and truck, of this types are declared.

Objects of type vehicle can be created separately after declaring structure as below:

struct vehicle {
  char* make;
  int year;
}; 
vehicle car, truck;

Once the object of structure is created, its members can be accessed directly. The syntax for that is simply to insert a dot (.) between the object name and the member name.

For example, 

car.make; 
truck.make;

The following program makes idea more clear.

// example of structures
#include <stdio.h>

struct vehicle {
  char* make;
  int year;
} car;

int main(){
    car.make = "Nissan";
    car.year = 2004;

    printf("Vehicle info: \n");
    printf("Make: %s \n",car.make);
    printf("Year: %d \n",car.year);
}

The output of the program is:

Vehicle info: 
Make: Nissan 
Year: 2004

The example shows that an object of structure act just as regular variables. Also, the members of structure are just regular variables. For example, the member car.year is a valid variable of type int, and car.make is a valid variable of type string.

C Pointers