programming in c structs and unions. no classes in c because c is not an oop language, there is no...

23
Programming in C Structs and Unions Structs and Unions

Upload: hannah-norman

Post on 24-Dec-2015

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Programming in C

Structs and UnionsStructs and Unions

Page 2: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

No Classes in C

• Because C is not an OOP language, there is no Because C is not an OOP language, there is no way to combine data and code into a single way to combine data and code into a single entity. entity.

• C does allow us to combine related data into a C does allow us to combine related data into a structure using the keyword structure using the keyword struct. .

• All data in a All data in a struct variable can be accessed by variable can be accessed by any code.any code.

• Think of a Think of a struct as an OOP class in which all as an OOP class in which all data members are public, and which has no data members are public, and which has no methods.methods.

Page 3: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Struct definition

• The general form of a structure definition is The general form of a structure definition is

struct tag{ member1_declaration; member2_declaration; member3_declaration; . . . memberN_declaration; };

where where struct is the keyword, is the keyword, tag names this kind of names this kind of struct, , and and member_declarations are variable declarations are variable declarations which define the members. which define the members.

Note the semi-colon

Page 4: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

C struct Example• Defining a Defining a struct to represent a point in a coordinate plane to represent a point in a coordinate plane

struct point{

int x; /* x-coordinate */int y; /* y-coordinate */

};

• Given the declarations Given the declarations

struct point p1;struct point p2;

we can access the members of these we can access the members of these struct variables: variables:

* the x-coordinate of p1 is * the x-coordinate of p1 is * the y-coordinate of p1 is* the y-coordinate of p1 is* the x-coordinate of p2 is* the x-coordinate of p2 is* the y-coordinate of p2 is* the y-coordinate of p2 is

point is the struct tag

p1.xp1.yp2.xp2.y

Page 5: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Using structs and members

• Like other variable types, Like other variable types, struct variables (e.g. p1, p2) can variables (e.g. p1, p2) can be passed to functions as parameters and returned from be passed to functions as parameters and returned from functions as return types.functions as return types.

• The members of a The members of a struct are variables just like any other are variables just like any other and ca be used wherever any other variable of the same type and ca be used wherever any other variable of the same type may be used. For example, the members of the may be used. For example, the members of the struct point can then be used just like any other integer variables. can then be used just like any other integer variables.

Page 6: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

printPoint.c// struct point is a function parametervoid printPoint( struct point aPoint ){

printf (“( %2d, %2d )”, aPoint.x, aPoint.y);}

// struct point is the return typestruct point inputPoint( ){

struct point inPoint;printf(“please input the x- and y-coordinates: “);scanf(“%d %d”, &inPoint.x, &inPoint.y);return inPoint;

}

int main ( ){

struct point endpoint; // endpoint is a struct point variableendpoint = inputPoint( ); // struct assignment.... more laterprintPoint( endpoint );return 0;

}

Page 7: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Initializing A struct

• A A struct variable may be initialized when it is variable may be initialized when it is declared by providing the initial values for each declared by providing the initial values for each member in the order they appearmember in the order they appear

struct point middle = { 6, -3 };

definesdefines thethe struct point variablevariable namednamed middle andand initializesinitializes middle.x = 6 andand middle.y = -3

Page 8: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

struct Variants• struct variables may be declared at the same time variables may be declared at the same time

the struct is definedthe struct is defined

struct point {

int x, y;

} endpoint, upperLeft;

defines the structure named point AND declares the variables endpoint and upperLeft to be of this type.

Page 9: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

struct typedef

• It’s common to use a It’s common to use a typedef for the name of a for the name of a struct to make code more concise. to make code more concise.

typedef struct point {int x, y;

} POINT;

defines the structure named point and defines POINT as a typedef (alias) for the struct. We can now declare variables, parameters, etc., asstruct point endpoint; or asPOINT upperRight;

Page 10: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

struct assignment

• The contents of a The contents of a struct variable may be copied to variable may be copied to another another struct variable of the same type using the variable of the same type using the assignment (=) operatorassignment (=) operator

• After this code is executedAfter this code is executed

struct point p1;struct point p2;p1.x = 42;p1.y = 59;

p2 = p1; /* structure assignment copies members */

The values of The values of p2’s members are the same as ’s members are the same as p1’s members.’s members.E.g. E.g. p1.x = p2.x = 42 and and p1.y = p2.y = 59

Page 11: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

struct within a struct• A data element in a A data element in a struct may be another may be another struct

(similar to composition with classes in Java / C++).(similar to composition with classes in Java / C++).• This example defines a line in the coordinate plane by This example defines a line in the coordinate plane by

specifying its endpoints as POINT specifying its endpoints as POINT structs

typedef struct line{POINT leftEndPoint;POINT rightEndPoint;

} LINE;

• Given the declarations below, how do we access the x- and Given the declarations below, how do we access the x- and y-coodinates of each line’s endpoints?y-coodinates of each line’s endpoints?

struct line line1, line2;line1.leftEndPoint.x line1.rightEndPoint.y

line2.leftEndPoint.x line2.rightEndPoint.y

Page 12: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

1/20/10 12

Arrays of struct• Since a Since a struct is a variable type, we can create is a variable type, we can create

arrays of arrays of structs just like we create arrays of just like we create arrays of primitives.primitives.

• Write the declaration for an array of 5 line structures Write the declaration for an array of 5 line structures name “lines”name “lines”

struct line lines[ 5 ]; oror

LINE lines[ 5 ];

• Write the code to print the x-coordinate of the left Write the code to print the x-coordinate of the left end point of the 3rd line in the arrayend point of the 3rd line in the arrayprintf( “%d\n”, lines[2].leftEndPoint.x);

Page 13: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

13

Array of struct Code/* assume same point and line struct definitions */

int main( )

{

LINE sides[5];

int k;

/* write code to initialize all data members to zero */

for (k = 0; k < 5; k++)

{

sides[k].leftEndPoint.x = 0;

sides[k].leftEndPoint.y = 0;

sides[k].rightEndPoint.x = 0;

sides[k].rightEndPoint.y = 0;

}

/* call the printPoint( ) function to print

** the left end point of the 3rd line */

printPoint( sides[2].leftEndPoint);

return 0;

}

Page 14: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Arrays within a struct

• Structs may contain arrays as well as primitive typesStructs may contain arrays as well as primitive types

struct month

{

int nrDays;

char name[ 3 + 1 ];

};

struct month january = { 31, “JAN”};

Page 15: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

A bit more complex

struct month allMonths[ 12 ] = {

{31, “JAN”}, {28, “FEB”}, {31, “MAR”},

{30, “APR”}, {31, “MAY”}, {30, “JUN”},

{31, “JUL”}, {31, “AUG”}, {30, “SEP”},

{31, “OCT”}, {30, “NOV”}, {31, “DEC”}

};

// write the code to print the data for September

printf( “%s has %d days\n”,

allMonths[8].name, allMonths[8].nrDays);

// what is the value of allMonths[3].name[1]

P

Page 16: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Bitfields

• When saving space in memory or a communications When saving space in memory or a communications message is of paramount importance, we sometimes need message is of paramount importance, we sometimes need to pack lots of information into a small space. We can use to pack lots of information into a small space. We can use struct syntax to define “variables” which are as small as 1 syntax to define “variables” which are as small as 1 bit in size. These variables are known as “bit in size. These variables are known as “bit fields”.”.

struct weather

{unsigned int temperature : 5;

unsigned int windSpeed : 6;

unsigned int isRaining : 1;

unsigned int isSunny : 1;

unsigned int isSnowing : 1;

};

Page 17: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Using Bitfields

• Bit fields are referenced like any other struct memberBit fields are referenced like any other struct memberstruct weather todaysWeather;

todaysWeather.temperature = 44;todaysWeather.isSnowing = 0;todaysWeather.windSpeed = 23;/* etc */

if (todaysWeather.isRaining)printf( “%s\n”, “Take your umbrella”);

if (todaysWeather.temperature < 32 )printf( “%s\n”, “Stay home”);

Page 18: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

More on Bit fields

• Almost everything about bit fields is implementation Almost everything about bit fields is implementation (machine and compiler) specific.(machine and compiler) specific.

• Bit fields may only defined as Bit fields may only defined as (unsigned) ints• Bit fields do not have addresses, so the Bit fields do not have addresses, so the & operator operator

cannot be applied to themcannot be applied to them

• We’ll see more on this laterWe’ll see more on this later

Page 19: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Unions

• A A union is a variable type that may hold different is a variable type that may hold different type of members of different sizes, BUT only one type of members of different sizes, BUT only one type at a time. type at a time. All members of the union share the same memory. The compiler assigns enough . The compiler assigns enough memory for the largest of the member types.memory for the largest of the member types.

• The syntax for defining a The syntax for defining a union and using its and using its members is the same as the syntax for a members is the same as the syntax for a struct..

Page 20: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Formal Union Definition

• The general form of a The general form of a unionunion definition is definition is union tag{ member1_declaration; member2_declaration; member3_declaration; . . . memberN_declaration; };

where where union is the keyword, is the keyword, tagtag names this kind of names this kind of union, , and and mmember_declarations are variable declarations are variable declarations which define the members. Note that the syntax for defining a which define the members. Note that the syntax for defining a union is exactly the same as the syntax for a is exactly the same as the syntax for a struct..

Page 21: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

An application of Unions

struct square { int length; };struct circle { int radius; };struct rectangle { int width; int height; };enum shapeType {SQUARE, CIRCLE, RECTANGLE };

union shapes{

struct square aSquare;struct circle aCircle;struct rectangle aRectangle;

};

struct shape {

enum shapeType type;union shapes theShape;

};

Page 22: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

An application of Unions (2)

double area( struct shape s){

switch( s.type ) {case SQUARE:

return s.theShape.aSquare.length* s.theShape.aSquare.length;

case CIRCLE:return 3.14 *

s.theShape.aCircle.radius * s.theShape.aCircle.radius;

case RECTANGLE :return s.theShape.aRectangle.height

* s.theShape.aRectangle.width;}

}

Page 23: Programming in C Structs and Unions. No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity.Because

Union vs. Struct

• SimilaritiesSimilarities– Definition syntax virtually identical– Member access syntax identical

• DifferencesDifferences– Members of a struct each have their own address in

memory. – The size of a struct is at least as big as the sum of the

sizes of the members (more on this later)– Members of a union share the same memory. – The size of a union is the size of the largest member.