0% found this document useful (0 votes)
8 views

Lecture 3 - Pointers, Reference and Structured Data

The document discusses structures in C++. Structures allow grouping of multiple variables of different types together under one name. Structures can contain member variables of basic types like int and string, which are accessed using the dot operator. Arrays of structures can also be defined to store multiple structured records.

Uploaded by

HuayiLI1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture 3 - Pointers, Reference and Structured Data

The document discusses structures in C++. Structures allow grouping of multiple variables of different types together under one name. Structures can contain member variables of basic types like int and string, which are accessed using the dot operator. Arrays of structures can also be defined to store multiple structured records.

Uploaded by

HuayiLI1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Computer Aided Engineering

Lecture 3
Pointers, References and Structured Data

C.F. Kwong
[email protected]
Department of Electrical and Electronic Engineering
Faculty of Science and Engineering
Room: PMB 325
Topics
Revision of Pointers and References
Structures
Unions
Enumerators
Getting the Address of a Variable
Each variable in program is stored at a unique
address
Use address operator & to get address of a variable:
int num = -99;
cout << &num; // prints address
// in hexadecimal
Pointer Variables
Pointer variable : Often just called a pointer, it's a
variable that holds an address
Because a pointer variable holds the address of
another piece of data, it "points" to the data
Definition:
int *intptr;
Read as:
“intptr can hold the address of an int”
Spacing in definition does not matter:
int * intptr; // same as above
int* intptr; // same as above
Pointer Variables
Assigning an address to a pointer variable:
int *intptr;
intptr = &num;
Memory layout:
Something Like Pointers : Arrays
The values parameter, in the showValues
function, points to the numbers array.

C++ automatically stores


the address of numbers in
the values parameter.
Something Like Pointers: Reference Variables

We have also worked with something like pointers when


we learned to use reference variables. Suppose we have
this function:
void getOrder(int &donuts)
{
cout << "How many doughnuts do you want? ";
cin >> donuts;
}
And we call it with this code:
int jellyDonuts;
getOrder(jellyDonuts);
Something Like Pointers: Reference Variables

The donuts parameter, in the getOrder function,


points to the jellyDonuts variable.

C++ automatically stores


the address of
jellyDonuts in the
donuts parameter.
The Relationship Between Arrays and Pointers

Array name is starting address of array


int vals[] = {4, 7, 11};

4 7 11
starting address of vals: 0x4a00
cout << vals; // displays
// 0x4a00
cout << vals[0]; // displays 4
The Relationship Between Arrays and Pointers
Array name can be used as a pointer constant:
int vals[] = {4, 7, 11};
cout << *vals; // displays 4
Pointer can be used as an array name:
int *valptr = vals;
cout << valptr[1]; // displays 7
Pointers in Expressions

Given:
int vals[]={4,7,11}, *valptr;
valptr = vals;

What is valptr + 1? It means (address in


valptr) + (1 * size of an int)
cout << *(valptr+1); //displays 7
cout << *(valptr+2); //displays 11

Must use ( ) as shown in the expressions


Array Access

Array elements can be accessed in many ways:


Array access method Example

array name and [] vals[2] = 17;

pointer to array and [] valptr[2] = 17;

array name and subscript *(vals + 2) = 17;


arithmetic
pointer to array and *(valptr + 2) = 17;
subscript arithmetic
Array Access

Conversion: vals[i] is equivalent to *(vals


+ i)
No bounds checking performed on array access,
whether using array name or a pointer
From Program 9-7
Pointer Arithmetic

Operations on pointer variables:


Operation Example
int vals[]={4,7,11};
int *valptr = vals;

++, -- valptr++; // points at 7


valptr--; // now points at 4
+, - (pointer and int) cout << *(valptr + 2); // 11

+=, -= (pointer valptr = vals; // points at 4


and int) valptr += 2; // points at 11
- (pointer from pointer) cout << valptr–val; // difference
//(number of ints) between valptr
// and val
From Program 9-9
Initializing Pointers

Can initialize at definition time:


int num, *numptr = &num;
int val[3], *valptr = val;
Cannot mix data types:
double cost;
int *ptr = &cost; // won’t work
Can test for an invalid address for ptr with:
if (!ptr) ...
Example
int x = 25;
int *intptr = &x;
cout << *intptr << endl;

//This prints 25.


Comparing Pointers
Relational operators (<, >=, etc.) can be used to
compare addresses in pointers
Comparing addresses in pointers is not the same as
comparing contents pointed at by pointers:
if (ptr1 == ptr2) // compares
// addresses
if (*ptr1 == *ptr2) // compares
// contents
Pointers as Function Parameters

A pointer can be a parameter


Works like reference variable to allow change to
argument from within function
Requires:
1) asterisk * on parameter in prototype and heading
void getNum(int *ptr); // ptr is pointer to an int
2) asterisk * in body to dereference the pointer
cin >> *ptr;
3) address as argument to the function
getNum(&num); // pass address of num to getNum
Example

void swap(int *x, int *y)


{ int temp;
temp = *x;
*x = *y;
*y = temp;
}

int num1 = 2, num2 = -3;


swap(&num1, &num2);
Pointers as Function Parameters in Program 9-11

(Program Continues)
Pointers as Function Parameters in Program 9-11
Pointers to Constants
If we want to store the address of a constant in a
pointer, then we need to store it in a pointer-to-
const.
Example: Suppose we have the following definitions:

const int SIZE = 6;


const double payRates[SIZE] =
{ 18.55, 17.45, 12.85,
14.97, 10.35, 18.89 };
In this code, payRates is an array of constant
doubles.
Pointers to Constants

Suppose we wish to pass the payRates array to a


function? Here's an example of how we can do it.

void displayPayRates(const double *rates, int size)


{
for (int count = 0; count < size; count++)
{
cout << "Pay rate for employee " << (count + 1)
<< " is $" << *(rates + count) << endl;
}
}

The parameter, rates, is a pointer to const double.


Declaration of a Pointer to Constant
Constant Pointers
A constant pointer is a pointer that is initialized with
an address, and cannot point to anything else.

Example

int value = 22;


int * const ptr = &value;
Dynamic Memory Allocation
Can allocate storage for a variable while program is
running
Computer returns address of newly allocated
variable
Uses new operator to allocate memory:
double *dptr = nullptr;
dptr = new double;
new returns address of memory location
Releasing Dynamic Memory

Use delete to free dynamic memory:


delete fptr;
Use [] to free dynamic array:
delete [] arrayptr;
Only use delete with dynamic memory!
Dynamic Memory Allocation in Program 9-14
Dynamic Memory Allocation in Program 9-14

Program 9-14 (Continued)


Dynamic Memory Allocation in Program 9-14
Program 9-14 (Continued)

Notice that in line 49 nullptr is assigned to the sales


pointer. The delete operator is designed to have no
effect when used on a null pointer.
Read Chapter 9
Topics
Revision of Pointers and References
Structures
Unions
Enumerators
Abstract Data Type (ADT)
A data type that specifies values that can be stored
operations that can be done on the values
User of an abstract data type does not need to know
the implementation of the data type, e.g., how the
data is stored
ADTs are created by programmers
Combining Data into Structures
Structure: C++ construct that allows multiple
variables to be grouped together
General Format:

struct <structName>
{
type1 field1;
type2 field2;
. . .
};
Example struct Declaration
struct Student Structure tag
{
int studentID;
string name;
Structure members
short yearInSchool;
double gpa;
};
Must have ; after closing }
struct names commonly begin with uppercase
letter
Defining Variables
struct declaration does not allocate memory or
create variables
To define variables, use structure tag as type name:

Student bill;
Assessing Structure Members
Use the dot (.) operator to refer to members of
struct variables:

cin >> stu1.studentID;


getline(cin, stu1.name);
stu1.gpa = 3.75;

Member variables can be used in any manner


appropriate for their data type
Displaying a struct Variables
To display the contents of a struct variable, must
display each field separately, using the dot operator:

cout << bill; // won’t work


cout << bill.studentID << endl;
cout << bill.name << endl;
cout << bill.yearInSchool;
cout << " " << bill.gpa;
Comparing struct Variables
Cannot compare struct variables directly:

if (bill == william) // won’t work

Instead, must compare on a field basis:

if (bill.studentID ==
william.studentID) ...
Initialising a Structure
struct variable can be initialized when defined:
Student s = {11465, "Joan", 2, 3.75};

Can also be initialized member-by-member after


definition:
s.name = "Joan";
s.gpa = 3.75;
More on Initialising a Structure
May initialize only some members:
Student bill = {14579};
Cannot skip over members:
Student s = {1234, "John", ,
2.83}; // illegal
Cannot initialize in the structure declaration, since
this does not allocate memory
Arrays of Structures
Structures can be defined in arrays
Can be used in place of parallel arrays
const int NUM_STUDENTS = 20;
Student stuList[NUM_STUDENTS];

Individual structures accessible using subscript


notation
Fields within structures accessible using dot
notation:
cout << stuList[5].studentID;
Nested Structures
A structure can contain another structure as a member:
struct PersonInfo
{ string name,
address,
city;
};

struct Student
{ int studentID;
PersonInfo pData;
short yearInSchool;
double gpa;
};
Members of Nested Structures
Use the dot operator multiple times to refer to fields
of nested structures:

Student s;
s.pData.name = "Joanne";
s.pData.city = "Tulsa";
Structures as Function Arguments
May pass members of struct variables to functions:
computeGPA(stu.gpa);
May pass entire struct variables to functions:
showData(stu);
Can use reference parameter if function needs to
modify contents of structure variable
Excerpts from Program 11-6
Structures as Function Arguments - Notes
Using value parameter for structure can slow down a
program, waste space
Using a reference parameter will speed up program,
but function may change data in structure
Using a const reference parameter allows read-only
access to reference parameter, does not waste space,
speed
Revised showItem Function
Returning a Structure from a Function
Function can return a struct:
Student getStudentData(); // prototype
stu1 = getStudentData(); // call

Function must define a local structure


– for internal use
– for use with return statement
Returning a Structure from a Function –
Example
Student getStudentData()
{ Student tempStu;
cin >> tempStu.studentID;
getline(cin, tempStu.pData.name);
getline(cin, tempStu.pData.address);
getline(cin, tempStu.pData.city);
cin >> tempStu.yearInSchool;
cin >> tempStu.gpa;
return tempStu;
}
Pointers to Structures
A structure variable has an address
Pointers to structures are variables that can hold the
address of a structure:
Student *stuPtr;
Can use & operator to assign address:
stuPtr = & stu1;
Structure pointer can be a function parameter
Accessing Structure Members via Pointer
Variables
Must use () to dereference pointer variable, not field
within structure:
cout << (*stuPtr).studentID;

Can use structure pointer operator to eliminate ()


and use clearer notation:
cout << stuPtr->studentID;
Example
Topics
Structures
Unions
Enumerators
Union
Similar to a struct, but
– all members share a single memory location, and
– only one member of the union can be used at a time
Declared using union, otherwise the same as
struct
Variables defined as for struct variables
Anonymous Union
A union without a union tag:
union
{
...
};

Must use static if declared outside of a function


Allocates memory at declaration time
Can refer to members directly without dot operator
Uses only one memory location, saves space
Topics
Structures
Unions
Enumerators
Enumerated Data Types
An enumerated data type is a programmer-defined
data type. It consists of values known as
enumerators, which represent integer constants.
Example:
enum Day { MONDAY, TUESDAY,
WEDNESDAY, THURSDAY,
FRIDAY };
The identifiers MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, and FRIDAY, which are listed inside the
braces, are enumerators. They represent the values
that belong to the Day data type.
Enumerated Data Types
Once you have created an enumerated data type in
your program, you can define variables of that type.
Example:
Day workDay;
This statement defines workDay as a variable of the
Day type.
Enumerated Data Types
We may assign any of the enumerators MONDAY,
TUESDAY, WEDNESDAY, THURSDAY, or FRIDAY to a
variable of the Day type. Example:

workDay = WEDNESDAY;

Note that the enumerators are not strings, so they


aren’t enclosed in quotes. They are identifiers. For
example, this would be wrong:

workDay = “WEDNESDAY”; ✗
Enumerated Data Types
So, what is an enumerator?
Think of it as an integer named constant
Internally, the compiler assigns integer values to the
enumerators, beginning at 0.

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY,


FRIDAY };
In memory...
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
THURSDAY = 3
FRIDAY = 4
Enumerated Data Types
Using the Day declaration, the following code...
cout << MONDAY << " "
<< WEDNESDAY << " “
<< FRIDAY << endl;
...will produce this output:
0 2 4
Assigning an integer to an enum Variable
} You cannot directly assign an integer value to an
enum variable. This will not work:
workDay = 3; // Error! ✗

Instead, you must cast the integer:


workDay = static_cast<Day>(3); ✔
Assigning an Enumerator to an int Variable
You CAN assign an enumerator to an int variable.
For example:

int x;
x = THURSDAY;

This code assigns 3 to x.


Comparing Enumerator Values
Enumerator values can be compared using the
relational operators. For example, using the Day data
type the following code will display the message
"Friday is greater than Monday.“

if (FRIDAY > MONDAY)


{
cout << "Friday is greater "
<< "than Monday.\n";
}
Cont …
Anonymous Enumerated Types
An anonymous enumerated type is simply one that
does not have a name. For example, in Program 11-
13 we could have declared the enumerated type as:

enum { MONDAY, TUESDAY,


WEDNESDAY, THURSDAY,
FRIDAY };
Using Math Operators with enum Variables
You can run into problems when trying to perform
math operations with enum variables. For example:
Day day1, day2; // Define two Day variables.
day1 = TUESDAY; // Assign TUESDAY to day1.
day2 = day1 + 1;// ERROR! Will not work! ✗
The third statement will not work because the
expression day1 + 1 results in the integer value 2,
and you cannot store an int in an enum variable.
You can fix this by using a cast to explicitly convert
the result to Day, as shown here:
// This will work.
day2 = static_cast<Day>(day1 + 1); ✔
Using an enum Variable to Step through an
Array’s Element
Because enumerators are stored in memory as integers,
you can use them as array subscripts.
For example:
enum Day { MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY };
const int NUM_DAYS = 5;
double sales[NUM_DAYS];
sales[MONDAY] = 1525.0;
sales[TUESDAY] = 1896.5;
sales[WEDNESDAY] = 1975.63;
sales[THURSDAY] = 1678.33;
sales[FRIDAY] = 1498.52;
Using an enum Variable to Step through an
Array’s Element
Remember, though, you cannot use the ++ operator
on an enum variable. So, the following loop will NOT
work.
for (workDay = MONDAY; workDay <= FRIDAY; workDay++)
{
……
} ✗
You must rewrite the loop’s update expression using
a cast instead of ++:
for (workDay = MONDAY; workDay <= FRIDAY;
workDay = static_cast<Day>(workDay + 1))
{
……
} ✔
Enumerators Must Be Unique Within the same
Scope
Enumerators must be unique within the same scope.
(Unless strongly typed)
For example, an error will result if both of the
following enumerated types are declared within the
same scope:

enum Presidents { MCKINLEY, ROOSEVELT, TAFT };


enum VicePresidents { ROOSEVELT, FAIRBANKS,
SHERMAN };

ROSEVELT is declared twice


Questions?

You might also like