Structures

Collection of different data types under a single identifier name, terminated with a semi-colon ;

 

Declared as follows:

 

struct identifier {

member1 ;

member2 ;

memberN ;

} ;

 

e.g.

struct bike {

char rider[ ] ;

int place ;
float speed ;
} ;

 

Once declared, the named structure creates a new data type that can be used just like any other data type:

 

data type identifier ; //e.g. int myVar ;

bike ducati ;
bike yamaha, honda ;

 

Alternatively a structure can be declared with identifiers after the closing } and before the ; as follows:

 

struct bike {

char rider[ ] ;

int place ;
float speed ;
} ducati, yamaha, honda ;

 

Individual members can be referred to by using the . dot member operator, which connects the structure name with the member name:

 

ducati.speed

 

#include <stdio.h>

struct bike {
	char rider[10] ;
	int place ;
	float speed ;
} yamaha = {"Lorenzo", 1, 254.12};

/*the last lines declares & defines the yamaha bike structure with all values*/

int main() {

	/*declare & define the honda bike structure with all values*/
	struct bike honda = {"Pedrosa", 2, 267.83} ;

	/*declare the ducati bike structure and initialise just the first member
	leaving the other members blank*/
	struct bike ducati = {"Valentino"} ;
	/*now provide values for the other members*/
	ducati.place = 6 ;
	ducati.speed = 246.87 ;

	struct bike pramac = {"DePuniet"} ; //just declaring and initialising the first member

	struct bike proton ; //just declaring with no values

	printf("%s, %3.2f, %d \n", yamaha.rider, yamaha.speed, yamaha.place);
	printf("%s, %3.2f, %d \n", honda.rider, honda.speed, honda.place);
	printf("%s, %3.2f, %d \n", ducati.rider, ducati.speed, ducati.place);
	printf("%s, %3.2f, %d \n", pramac.rider, pramac.speed, pramac.place);
	printf("%s, %3.2f, %d \n", proton.rider, proton.speed, proton.place);

	return 0;
}

Compile & run:

Lorenzo, 254.12, 1
Pedrosa, 267.83, 2
Valentino, 246.87, 6
DePuniet, 0.00, 0
, 0.00, 0

 

 


 

typedef struct

provides a shortcut instead of having to write out the full syntax, struct myStruct { . . . } ;

 

typedef struct identifier {

int memberOne ;

char memberTwo ;

float memberThree ;

} myStruct ;

 

myStruct can now be used instead of having to use the keyword, struct, before each declaration of a new structure.

Leave a Reply