Structs

From Wikiversity
Jump to: navigation, search

Structures allow objects of different types to be stored within one object. Let's say that you want to store a car's colour, maximum speed and registration number. We can define a structure that includes all that information.

First, include the header files required for printf and strcpy:

#include <stdio.h>
#include <string.h>

Define the structure:

struct car
{
       unsigned int colour;
       unsigned int max_speed;
       char reg_num[10];
};

Proved example of the structure being used:

int main(void)
{
 
     /* define two car objects */
     struct car car_1, car_2;
 
     car_1.colour     = 1;   /* initialize car_1's colour */
     car_1.max_speed  = 200; /* initialize car_1's speed */
 
     /* initialize the reg number */
     strcpy(car_1.reg_num, "MG 100");
 
     /* copy car_1 data to car_2 */
     car_2 = car_1;
 
     /* print the values */
     printf("Colour = %u\n", car_2.colour);
     printf("Speed  = %u\n", car_2.max_speed);
     printf("Reg    = %s\n", car_2.reg_num);
 
     /* indicate  success */
     return 0;
}


Project: Topic:C
Previous: Pointers and Arrays — Structs — Next: Input and Output