Structures

Structures provide a way to group data logically with each occurrence of a structure containing the same data types in the same order. Once a structure is defined, it can be used to define any number of structure variables. Some of the ways structures can be used:

  • can be written to disk
  • can be passed to a function
  • can be used with arrays, creating arrays of structures

One  |  Array

One

This example uses one structure, named Point, and one structure variable, named OnePoint, to demonstrate the basics of structure definition and usage. OnePoint is a variable that contains variables and requires dot notation to reference the variables inside the structure. The Point structure contains x,y coordinates and a letter.

The variables x and y in main() just happen to be named the same as x and y in the structure Point, but they are two completely different variables.

#include <stdio.h>

struct Point
{
  int  x;
  int  y;
  char OneCharacter;
};

int main(int argc, char *argv[])
{
  int x;
  int y;
  struct Point OnePoint;

  OnePoint.x = 37;
  OnePoint.y = 21;
  OnePoint.OneCharacter = 'g';

  x = OnePoint.x;
  y = OnePoint.y;
  printf("x is %d     y is %d\n", x, y);
  printf("and the character is %c\n", OnePoint.OneCharacter);

  return 0;
}
Top

Array

This example is similar to the previous example, except it has an array of Point structures. The name of the array is OnePoint and it has two elements.

#include <stdio.h>

struct Point
{
  int  x;
  int  y;
  char OneCharacter;
};

int main(int argc, char *argv[])
{
  int i;
  int x;
  int y;
  struct Point OnePoint[2];

  OnePoint[0].x = 37;
  OnePoint[0].y = 21;
  OnePoint[0].OneCharacter = 'g';

  OnePoint[1].x = 73;
  OnePoint[1].y = 12;
  OnePoint[1].OneCharacter = 'j';

  for (i = 0; i <= 1; i++)
  {
    x = OnePoint[i].x;
    y = OnePoint[i].y;
    printf("x is %d   y is %d\n", x, y);
    printf("and the character is %c\n", OnePoint[i].OneCharacter);
  }

  return 0;
}
Top