MODULE 5 : Basic Input and Output (I/O),
Functions, Pointers and References Loops
and Conditional Statements
Objectives
By the end of this module, you will be able
to:
Understand working with strings
Implement pointers
Know how to use References
Identify the strength of pointers
MODULE –5: Basic Input and Output (I/O),
Functions, Pointers and References Loops
and Conditional Statements
UNIT –5.1 The string concept
UNIT –5.2 Data Variables and Memory
UNIT –5.3 Reserving Memory
UNIT –5.4 Pointers
UNIT –5.5 Function challenge
UNIT –5.6 Pointers and Functions
UNIT –5.7 Functions and references
UNIT –5.8 Comparing pointers and references:
5.1 The string concepts:
Declare a string variable
string variableName;
Read in a string
cin>>variableName;
Display a string
cout<<variableName<<endl;
Assign a value to a string variable
variableName = “something”; //e.g. name =
“Babcock”;
5.2 Data Variables and Memory
When a data variable is declared in a
program, physical memory in the random
access memory (RAM) is reserved for the
variable.
The number of memory bytes that are
actually used depends on the data type of
the variable.
E.g.
char uses1bytes with precision range of -
128 to 127
sizeof Operator
C++ provides the sizeof operator, which
returns the number of bytes reserved for
either a data type or a variable.
The form for the sizeof operator is:
sizeof (data_type); //for a data type (must
be in parentheses)
sizeof variable_name; //for variable
name the use of “()” is optional
5.3 Reserving Memory
The computer reserves actual memory locations for program
variables.
If the variables are declared inside a function, they are placed
on the stack.
The stack is a region of memory reserved for program
variables.
The first variable that is declared is placed at the far end of
the stack.
Data variables are stacked into memory, and the first variable
—because it is located at the end of the stack—has the
highest address.
The following figure illustrates how the six variables in the
declaration statements above are reserved in memory.
The boxes in the figure represent the memory for each
variable.
Arrangement of data in memory as they are
declared
Address Operator: &
Data types each hold a type of data such as numeric or
character.
Each variable has a data type, name, value, and address.
To access the address, C++ provides the address operator,
&.
When used with a data variable, the address operator gives
the address in memory of the data variable.
Example:
int number = 5;
Data Type: int
Name: number
Value: 5
Mem. Address: 0x0066FDF4
Mem. Size: 4 bytes
TUTOR MARKED ASSESSMENT (TMA)
Assignments/Tasks for the students:
1. Where and when is address operator “&” used
2. What is the byte allocation for double as a primitive data type
3. What should inform my use of int or long int? Give example.
5.4 Pointers
A pointer is a data type that holds a
hexadecimal address, such as 0x0066FDF4.
A pointer is meant to hold the address of a
specific variable.
When the pointer variable contains another
variable’s address, it is said that the pointer
“points to” that variable.
Pointers do not have their own keyword, but
have specific pointer declaration statements.
Pointers
Fig.5.5 sample code implementation showcasing the use
of pointer
Pointers
int count = 7;
int *countPtr = &count;
The program and the pointer need to know what
type of variable-address the pointer contains.
A pointer variable is declared by specifying the
data type to which it will be pointing.
The asterisk operator (*) is used in the
declaration statement.
Pointers
The format:
data_type *variable_name;
Many naming conventions are used with pointer variables
to help the programmer remember which variables are
pointers.
Three conventions are listed below:
float *x_ptr; // use extension _ptr
float *pX; // use lowercase p with capital letter
float *p_x; // use prefix p_
Declaring int and double variables and pointers:
int a = 75;
int *a_ptr;
double b = 82.0;
double *b_ptr;
Pointers
We have named our pointers a_ptr and b_ptr so
that we can keep track of which pointer variable
belongs with which variable.
C++ does not automatically assign the correct
address into the correct pointer.
The programmer having the address operator
does the address assignment.
Initialize pointers with 0, NULL or some address
to prevent pointing to unknown or uninitialized
areas of memory. Uninitialized pointer could
cause havoc to the system.
Pointers and the Address Operator
Dereferencing a Pointer *
Dereference: is to give us the value that the pointer
points to.
For instance
int count = 7;
int *countPtr = &count;
cout<<” \nThe first statement
output : ” <<count<<endl;
cout<<” \nThe second statement output :
”<<*countPtr<<endl;
Output:
The first statement output : 7
The second statement output : 7
Pointers and Functions
Pointers, address operator and the indirection operator solve the
problem of returning more than one data item from a function.
This technique allows us to perform a function call by reference
using pointers.
We introduce the indirection operator, the asterisk (*).
We explicitly pass the address of a variable to a function using the
address operator.
The function stores the address in a pointer variable.
It then uses the indirection operator to access the calling function’s
variables.
The indirection operator, when used with a pointer variable, tells the
program, “Go to the address that I am holding.”
The pointer/indirection operator combination can be used either to
assign a value or to get a value where the pointer is pointing.
sample code implementation using two pointers
//sample code implementation;
//prototype using two pointers
void AskForXandY(int *pX, int *pY);
int main()
{
int x,y;
AskForXandY(&x, &y); //pass address/memory location of
variables of function main
//and other codes here
}
void AskForXandY(int *pX, int *pY)
{
cout << "\n Enter the two integer values”;
cin >> *pX >> *pY;
}
Pointers and Functions
Note that we do not use the keyword, return, in this
function.
There is no need since we are using two pointers.
We could rewrite this program so that our
AskForXandY() function does return one value.
Whenever a function returns a value via the return
statement, you need to be sure to assign the value to a
variable.
passing address/memory location of
variables; main’s address
//prototype using one pointer and return value
int AskForXandY(int *pY);
int main()
{
int x,y;
x = AskForXandY(&y); // pass address/memory location of
variables; main’s address
// and other codes here
}
int AskForXandY(int *pY)
{
int x;
cout << "\n Enter two integer values”;
cin >> x >> *pY;
return x;
}
Returning a value to the calling
function, as well as using pointers.
Efficient Handling of Large Data Items
In early days of programming, pointers assisted the
programmer in writing memory efficient code.
Pointers can be quite useful in saving time and memory.
Normally, if a variable is passed to a function, the
function makes its own copy of the data. With a pointer,
the function accesses the data directly (not a copy). This
is why a change made is a permanent one.
If the program had large the data items (i.e., a 640 by
480 pixel color image is 900K bytes), it is best to have
only one copy of the data in the program (an advantage).
TUTOR MARKED ASSESSMENT (TMA)
Assignments/Tasks for the students:
1) Give a generic illustration of what pointer is about
2) What are the advantages of using pointers by a programmer
3) What is the result of the following code listing :
int item = 100;
int *Ptr = &item;
cout<<” \nThe first statement output : ” <<item<<endl;
cout<<” \nThe second statement output : ”<<(*Ptr + 10)<<endl;
Functions and references
In the call by reference with reference parameter passing
technique, the function prototype and function header line
contain reference parameters— the & is used instead of the *.
The & operator in the prototype and function header line is
saying “Reference” (as opposed to “Pointer”).
In the call statement, just the variable name is used; you do not
need to use the & operator.
In this new type of call by reference, the addresses are passed
to the called function and it accesses the calling function’s data.
The & operator is used in the function prototype and function
header line.
The call statement has the variable names in it, but their
addresses are being passed to the function.
Functions and references
//prototype using two references
void AskForXandY(int &rX, int &rY);
int main()
{
int x, y;
AskForXandY(x, y); //the call uses the variable names
AskForXandY(&x, &y); //line indicate addresses are
passed
//other codes in main follows
}
Functions and references
void AskForXandY(int &rX, int &rY)
{
cout << "\n Enter two integer variable values”;
cin >> rX >> rY;
}
//compare the above to this and spot the difference in
implementation style
void AskForXandY(int *Px, int *Py)
{
cout << "\n Enter two integer variable values”;
cin >> *Py >> *Py;
}
Reference Parameter Limitations
You may not reference another reference. (It
is possible to have a pointer to a pointer.)
A reference variable must be initialized when
declared if it is not part of a function
parameter list, or if it is not a return value or
class member.
It is not possible to create a pointer to a
reference or to create an array of references.
Always check that your call statements match the
input list!
Importance of Pointers
Secondly, pointers are required in order to
have your program perform dynamic
memory allocation.
Dynamic memory allocation is the technique
where your program reserves memory while it
runs instead of reserving memory statically.
C++ gives you an address of the memory it
reserved “on the fly” as your program runs.
Pointers are used to hold these memory
addresses.
Summary
A pointer and a reference are designed to hold a
hexadecimal address.
A pointer is declared using the * operator, a reference is
declared using an &.
During a call by reference using pointers, a variable’s
address is assigned explicitly into the pointer by use of
the address operator, &.
During a call by reference using references, a
variable’s name is used in the call statement, but
its address is passed to the function.
A pointer, when paired with the indirection operator,
accesses the data located at the address that it contains.
5.8 Comparing pointers and references:
END OF MODULE ASSESSMENT (EMA)
Assignments/Tasks for the students:
1) Describe with example what a pointer is.
2) State what can constitute problem when you are implementing
pointers
3) When is it advantageous to use pointers
4) Write a two function program (one main and the other
primeFunction) to detect if a supplied value is prime.