Structures

Structures

A facility for grouping data into composite forms. A collection of related elements, possible of different types.

struct fraction {
	int numerator;
	int denominator;
};

Usage:

struct fraction f1, f2;
f1.numerator = 22;
f1.denominator = 7;

f2 = f1; // copies over the whole struct

There are three ways to declare or define a structure:

  1. Variable structure
    • Cannot be passed to functions
    • This structure is a single variable
       struct {
        int a;
        int b;
       } foo;
      
  2. Tagged structure
    struct student {
     int id;
     char name[26];
     int gradepoints;
    };
    
  3. Type defined
    typedef struct {
     type1 fieldName1;
     type2 fieldName2;
     ...
     typeN fieldNameN;
    }tagName;
    

Pointers to structures

`typedef struct {
	int x;
	int y;
	float t;
	char u;
} SAMPLE;

SAMPLE sam1;
SAMPLE *pt;

ptr = &sam1;
(*ptr).y  == sam1.y


ptr->y // Name of pointer -> name of the field

Nesting structure

typedef struct {
	int month;
	int day;
	int year;
} DATE;

typedef struct {
	int hours;
	int min;
	int sec;
} TIME;

typedef struct {
	DATE date;
	TIME time;
} STAMP;

STAMP stamp; 

Arrays

A simple type of array in C is one that is declared in place. There are more complication use that are related to pointers.

int scores[100]; //0 to 99 hold 100 integers
Written on September 15, 2017