You are on page 1of 24

CS1010E Lecture 6

Structures
Henry Chia
hchia@comp.nus.edu.sg

Semester 1 2011 / 2012


Department of Computer Science
School Of Computing
National University Of Singapore

CS1010E Lecture 6 p.1/24

Lecture Outline
Structures.
Structure definition.
Declaration with structures.
Assigning structures.
Accessing members of a structure.
Using functions with structures.
Passing structures by value to a function.
Returning a structure from a function.
Problem solving involving structures.

CS1010E Lecture 6 p.2/24

Problem: Euclidean Distance


Write a function distance that finds the
straight line distance between two points
(x1 , y1 ) and (x2 , y2 ).
Analysis:
How do we represent a point in the
Cartesian plane? As two separate values,
or as one aggregate value?
Calculate the distance between two points
(x1 , y1 ) and (x2 , y2 ) using
p
distance = (x2 x1 )2 + (y2 y1 )2
CS1010E Lecture 6 p.3/24

Using Functions with Structures


double computeDist(double x1, double y1,
double x2, double y2)
{
double dx = x2 - x1, dy = y2 - y1;
return sqrt((dx*dx) + (dy*dy));
}
main

computeDist

x1

1.0

y1

1.0

x1

1.0

y1

1.0

x2

2.0

y2

2.0

x2

2.0

y2

2.0


distance

1.0,1.0,2.0,2.0

return 1.414..;

1.414..
distance = computeDist(x1,y1,x2,y2);
CS1010E Lecture 6 p.4/24

Structures
Thus far, declaring variables of int and double allow
us to work with individual numeric values.
To work with practical problems, each variable or value
may constitute a set of information/data record
A point (x, y) comprises two floating-point values.
A fraction xy comprises two integers for the
numerator and denominator.
A bank account is associated with an integer
account number, and a floating-point balance.
A structure defines a set of heterogeneous data for a
record, i.e. the individual parts of the data do not have
to be of the same type.

CS1010E Lecture 6 p.5/24

Structure Definition
struct struct_identifier
{
declarations
}; // Note the semi-colon

Examples of a structure definitions:


struct Point
{
double x, y;
};

struct Fraction
{
int num;
int den;
};

struct BankAccount
{
int accountNum;
double balance;
};

Structures defined above function prototypes.

CS1010E Lecture 6 p.6/24

General Form of a C program


Structures defined above function prototypes.
#include library_headers
#define CONSTANTS
struct struct_definitions
function_prototypes
int main(void)
{
declarations
statements
}
function_definitions
CS1010E Lecture 6 p.7/24

Structure Definition
Defining a structure is to define a new type.
struct Point
{
double x, y;
};

Structures are often called aggregate data


types, because they allow multiple data
values to be collected into a single data type.
Individual data values within a structure are
called data members, and each data
member has an identifier.
In the Point structure, x and y are members.
CS1010E Lecture 6 p.8/24

Declaration with Structures


Memory is not allocated for structure
definitions they only serve as blueprints for
declarations.
With the structure defined, we may proceeed
to declare variables of the structure type.
Following the struct Point definition, we
may now declare
struct Point pt1, pt2;

In the above, each variable pt1 and pt2


contains two data values the x and y
values associated with the point.
CS1010E Lecture 6 p.9/24

Declaration with Structures


The declaration statement
struct Point pt1;

allocates memory for the two data members


with no initial values; thus, their values are
unknown.
pt1

A structure variable is modeled using a variable


box, just like an int variable, but with richer
content.
CS1010E Lecture 6 p.10/24

Declaration with Structures


To initialize a structure variable during
declaration, the values are specified in a
sequence that is separated by commas and
enclosed in braces.
struct
struct
struct
struct

Point
Point
Point
Point

pt1={1.2,3.4};
unit={1};
origin={0};
pt2;

//
//
//
//

(1.2,3.4)
(1.0,0.0)
(0.0,0.0)
(?,?)

To zero a structure, just need to zero the first


member.
Use braces for initialization during
declaration only. Do not use braces for
assignment.
CS1010E Lecture 6 p.11/24

Assignment with Structures


Like primitive variables, a structure variable
can be assigned to structure variables of the
same structure type.
struct Point pt1={1.2,3.4}, pt2;

pt1

1.2

3.4

1.2

3.4

pt2

1.2

3.4

pt2 = pt1;

pt1

pt2

CS1010E Lecture 6 p.12/24

Member Operator
Arithmetic/relational/logical operations cannot
be applied on entire structure variables.
The operations above make sense only when
applied on specific data members.
A data member is referenced using the
structure variable name followed by the
structure member operator (.) and a data
member name.
Example, to compare points pt1 and pt2,
if (fabs(pt1.x - pt2.x) < EPSILON &&
fabs(pt1.y - pt2.y) < EPSILON )
printf("The two points are equal.\n");
CS1010E Lecture 6 p.13/24

Member Operator
Apart from initialization, structure variables
can also be assigned by assigning individual
data members.
pt1.x = 1.2;
pt1.y = 3.4;

By applying the member operator, the specific


member can be accessed and used in
statements, expressions, function arguments,
function return values, etc. without regards to
it being part of a structure.

CS1010E Lecture 6 p.14/24

Member Operator
For input and output, use scanf to read
values into the data members, and printf to
print their values.
The following reads a point (two floating point
values) as input, and outputs the point by
printing the individual x and y members.
struct Point pt1;
scanf("%lf %lf", &(pt1.x), &(pt1.y));
printf("The point is (%lf,%lf)\n",
pt1.x, pt1.y);

CS1010E Lecture 6 p.15/24

Structure as Function Parameter


Since structures behave like primitives, they
can be used as arguments to a function, and
a function can return one structure value.
When a structure variable is used as a
function argument, the entire content of the
structure is passed by value.
Write a function distance that finds the
straight line distance between two points
(x1 , y1 ) and (x2 , y2 ).
double distance(struct Point pt1,
struct Point pt2);

CS1010E Lecture 6 p.16/24

Structure as Function Parameter


double computeDist(struct Point pt1,
struct Point pt2)
{
double dx = pt1.x - pt2.x,
dy = pt1.y - pt2.y;
return sqrt((dx*dx) + (dy*dy));
}
main

computeDist

pt1

1.0 1.0

pt1

1.0 1.0

pt2

2.0 2.0

pt2

2.0 2.0


{1.0,1.0},{2.0,2.0}
distance

return 1.414..;

1.414..
distance = computeDist(pt1,pt2);

CS1010E Lecture 6 p.17/24

Returning a Structure
A function can be defined to return a single
value of type struct.
After the function is called, the entire structure
content is returned to the calling function.
Write a function midPoint that returns the
middle point between (x1 , y1 ) and (x2 , y2 ).
The midpoint (xm , ym ) is computed as
x 1 + x 2 y1 + y2
(xm , ym ) = (
,
)
2
2
struct midPoint(struct Point pt1,
struct Point pt2);
CS1010E Lecture 6 p.18/24

Returning a Structure
struct Point midPoint(struct
struct
{
struct Point midpt;
midpt.x = (pt1.x + pt2.x)
midpt.y = (pt1.y + pt2.y)
return midpt;
main
}
pt1

pt2

Point pt1,
Point pt2)
/ 2;
/ 2;
midPoint
pt1

1.0 1.0

pt2

2.0 2.0

1.0 1.0

2.0 2.0
{1.0,1.0},{2.0,2.0}

*
midpt

midpt

1.5 1.5


{1.5,1.5}

return midpt;

midpt = midPoint(pt1,pt2);
CS1010E Lecture 6 p.19/24

Ex: Overlapping Rectangles


A rectangle is well-defined using the
bottom-left and top-right points (xmin , ymin )
and (xmax , ymax ).
Write a function that determines if two input
rectangles overlap.
Analysis:
How do we represent a rectangle?
How do we check if two rectangles overlap
using their bottom-left and top-right
coordinates?

CS1010E Lecture 6 p.20/24

Ex: Overlapping Rectangles


#include <stdio.h>
struct Point
{
double x, y;
};
struct Rect
{
struct Point min, max;
};
int overlap(struct Rect r1, struct Rect r2);
struct Rect getRectangle();
struct Point getPoint();
int main(void)
{
struct Rect r1, r2;
r1 = getRectangle();
r2 = getRectangle();
if (overlap(r1,r2))
printf("Rectangles overlap.\n");
else
printf("Rectangles do not overlap.\n");
return 0;
}
CS1010E Lecture 6 p.21/24

Ex: Overlapping Rectangles


struct Rect getRectangle()
{
struct Rect r;
r.min = getPoint();
r.max = getPoint();
return r;
}
struct Point getPoint()
{
struct Point p;
scanf("%lf %lf", &(p.x), &(p.y));
return p;
}

CS1010E Lecture 6 p.22/24

Ex: Overlapping Rectangles


int overlap(struct Rect r1, struct Rect r2)
{
int noOverlap;
noOverlap = r1.min.x
r2.min.x
r1.min.y
r2.min.y

>
>
>
>

r2.max.x ||
r1.max.x ||
r2.max.y ||
r1.max.y;

return !noOverlap;
}

At times, it might be easier to work out the opposing


condition, e.g.not overlapping.
Apply the boolean negation operator ! on the opposing
condition to obtain the desired condition.
CS1010E Lecture 6 p.23/24

Lecture Summary
Definition of structures before usage
(declarations, functions, etc.)
Structures behave similarly to primitives.
Structure member operator .
Using functions with structures.
Pass-by-value/return of structures into/from
functions behave similarly to passing
primitives.

CS1010E Lecture 6 p.24/24

You might also like