You are on page 1of 54

POINTERS

SCHOOL OF COMPUTING MITCH M. ANDAYA


DATA TYPES AND THE MAIN MEMORY

• Basic C++ Data Types

– char - 8 bits or 1 byte

– int - 32 bits or 4 bytes

– float - 32 bits or 4 bytes

– double - 64 bits or 8 bytes

• Take note that the actual number of bits or bytes may


change depending on the computer system.

Pointers
DATA TYPES AND THE MAIN MEMORY

• Main Memory Representation

Example: 4GB (4,294,967,296 bytes) Main Memory

Memory Cell

Each memory
cell contains .
8-bits (1 byte) .
of data .

Pointers
DATA TYPES AND THE MAIN MEMORY

• To distinguish one memory cell from another, each cell is assigned a numeric
memory address starting at 0.

Memory Cell 0
Address of the 1st
Memory Cell
1
2
3
Each memory
cell contains .
8-bits (1 byte) .
of data .

4,294,967,294
4,294,967,295

Pointers
DATA TYPES AND THE MAIN MEMORY

• C++ stores the contents of a variable in the computer


system's main memory.

– Since a char variable occupies one byte, it is stored in


only one memory cell or location.
– Since an int variable occupies four bytes, it is stored in
four contiguous memory cells or locations.
– Since a float variable occupies four bytes, it is stored in
four contiguous memory cells or locations.
– Since a double variable occupies eight bytes, it is
stored in eight contiguous memory cells or locations.

Pointers
DATA TYPES AND THE MAIN MEMORY

• Example: char choice;

.
.
.
memory cell address of variable
allocated to 1,000 choice
variable choice 1,001
1,002 A C++ program
1,003 references a
variable by its
. name and not by
. its address (or
addresses) in main
. memory.

Pointers
DATA TYPES AND THE MAIN MEMORY

• If a variable occupies several memory cells, the address of that


variable is the address of the first memory cell allocated to it.

Example: int numb;

.
.
.
2,000
address of
memory cells variable numb
2,001
allocated to 2,002
variable numb 2,003
.
.
.

Pointers
DEFINITION OF A POINTER VARIABLE

• A pointer variable is a
variable that holds or
contains the memory
address of another variable.

• Pointer variables occupy 4


bytes or memory locations
(for a 32-bit computer
system) or 8 bytes or
memory locations (for a 64-
bit computer system).

Pointers
DEFINITION OF A POINTER VARIABLE

• If a pointer variable, p, is equal to the address of another variable


(choice), then p points to choice.

memory cells 3,000 Since p = 4,002 (the


allocated to 4,002
3,001 address of choice),
pointer 3,002 then p points to
variable p 3,003 choice.
.
.
.

4,000
memory cell 4,001
allocated to 4,002
address of
variable choice variable choice
4,003

Pointers
DEFINITION OF A POINTER VARIABLE

• If a pointer variable, p, points to an int, float, or double variable, it


is equal to the address of the first memory location only.

memory cells 3,000


Since p = 4,000 (the
allocated to 4,000
3,001
address of x), then
pointer 3,002
p points to x.
variable p 3,003

.
.
.

4,000
address of int
memory cells 4,001
variable x
allocated to int
4,002
variable x
4,003

Pointers
POINTER VARIABLE DECLARATION

• Pointer variable declaration is similar to the declaration of


regular variables.

The general format of a pointer declaration is:

data-type *var-name;

tells how to interpret


the contents of memory
starting at the address name of the
the pointer variable pointer variable
contains

Pointers
POINTER VARIABLE DECLARATION

• Examples:

char *x;
x is a pointer variable that can point to a char variable

int *y;
y is a pointer variable that can point to an int variable

float *z;
z is a pointer variable that can point to a float variable

Pointers
VISUAL REPRESENTATION OF POINTERS
p int

• The box on the left represents the pointer variable p while the box
on the right stands for as many memory cells as necessary to hold
the data type involved.

• In this example, since the data type is int, the right box represents
four contiguous memory cells or locations. The pointer variable p
actually points to the FIRST memory location only.

• In the diagram above, the value of the variable p is the address of


a location in memory and the contents of that memory location
are of type int.

Pointers
THE POINTER OPERATORS

• The & or "the address of" Operator – returns the memory address of the
operand. Use this operator to make a pointer point to a certain variable.

Example:
.
char y; .
char *p; .

p = &y; memory cell 1,000


allocated to
variable y 1,001
address of
1,002 variable y
1,003
the pointer variable p will contain .
the address of the variable y. So .
p = 1,002. In other words, the
pointer p points to y. .

Pointers
THE POINTER OPERATORS

• The * or the "the contents of" Operator – returns the value of the contents of
the variable being pointed at. More appropriately, * may be read as the "the
contents of the variable being pointed to by."

• Example: p is equal to the


address of y. So p
int y, x; points to y.
int *p;
x is equal to the
y = 25; contents of the
p = &y; variable being
pointed to by p.
x = *p;

The variable x will become equal to the contents of the variable being pointed to
by the pointer variable p (which is variable y). Therefore, x will become equal to
25.

Pointers
THE POINTER OPERATORS

• Sample Program 1:

#include <iostream>
using namespace std;

main()
{
int y, x;
int *p;
The output of this program will be:
y = 25;
p = &y; The value of y is 25
x = *p; The value of x is 25
The value of *p is 25
cout << "The value of y is " << y; The value of p is 0x22fd70
cout << "\nThe value of x is " << x;
cout << "\nThe value of *p is " << *p;
cout << "\nThe value of p is " << p;
}

Pointers
THE POINTER OPERATORS

• Sample Program 2:

#include <iostream>
using namespace std;

main()
{
int y;
int *p;
The output of this program will be:
p = &y;
Enter the value of y: 35
cout << "Enter the value of y: ";
cin >> *p; The value of y is 35.

cout << "\nThe value of y is " << y << ".";


}

Pointers
POINTER ASSIGNMENTS

• As with any variable, an assignment statement can have a pointer variable on


the right side of the assignment statement to assign its value to another
pointer. For example:

int x;
int *p1, *p2;

p1 = &x;
p2 = p1;

The statement p1 = &x will make the pointer variable p1 point to the integer
variable x.

The statement p2 = p1 will make the pointer variable p2 point to whatever


pointer variable p1 is pointing at.

Therefore, p2 now points to variable x also.

Pointers
POINTER ASSIGNMENTS

• Sample Program:

#include <iostream>
using namespace std;

main()
{
int y, x;
int *p1, *p2;
The output of this program will be:
y = 25;
p1 = &y; The value of y is 25
p2 = p1; The value of x is 25
x = *p2; The value of p1 is 0x22fd68
cout << "The value of y is " << y; The value of p2 is 0x22fd68
cout << "\nThe value of x is " << x;
cout << "\nThe value of p1 is " << p1;
cout << "\nThe value of p2 is " << p2;
}

Pointers
POINTERS AND FUNCTIONS

• Recall that one way of passing arguments to


functions is by using the call-by-value
technique.

This method copies the value of an argument


into a formal parameter of a function.

Changes made to the parameters of the


function have no effect on the variables used
to call it.

Pointers
POINTERS AND FUNCTIONS

• Sample Program 1: Write a program to prompt the user to enter the value of
the radius of a circle. The program will then compute the area of the circle and
then outputs the results. Use a function to compute the area.

#include <iostream>
using namespace std;
# define PI 3.1416 main()
{
float area, radius;
float comp_area (float
float rad)
rad
{ cout << "Please enter the radius: ";
float a; cin >> radius;

a = PI * rad * rad; area = comp_area(radius);


return (a);
} cout << "\nThe area is " << area << ".";
}

Pointers
POINTERS AND FUNCTIONS

• Sample Program 2: Rewrite the previous program to compute the area of a circle but this time,
add another function to prompt the user to enter the radius and return the value entered to
main().

#include <iostream> float comp_area (float rad)


using namespace std; {
# define PI 3.1416 float a;

a = PI * rad * rad;
float get_radius ()) return (a);
{ }
float r;
main()
cout << "Please enter the radius: "; {
cin >> r; float area, radius;

return (r); radius = get_radius();


} area = comp_area(radius);
cout << "\nThe area is " << area << ".";
}

Pointers
POINTERS AND FUNCTIONS

• The second method is the call-by-reference


method.

This technique copies the address of an argument


into the parameter.

Inside the function, the address is used to access


the actual argument used in the call.

In this method, changes made to the parameter


will affect the variable used to call the function.

Pointers
POINTERS AND FUNCTIONS
• Sample Program 3: Repeat the previous program but this time, modify the get_radius() function
such that the function should put the value entered by the user directly to the variable for the
radius of main(). No value should be returned.

#include <iostream>
using namespace std;
# define PI 3.1416

void get_radius (float


float *r)
*r
{
cout << "Please enter the radius: ";
main()
cin >> *r;
{
}
float area, radius;
float comp_area (float rad)
get_radius(&radius);
&radius
{
area = comp_area(radius);
float a;
cout << "\nThe area is " << area << ".";
a = PI * rad * rad;
}
return (a);
}

Pointers
POINTERS AND FUNCTIONS

• Sample Program 4: Repeat the previous program but this time, modify the comp_area() function
such that the function should put the value computed by the user directly to the variable for the
area of main(). No value should be returned.

#include <iostream>
using namespace std;
# define PI 3.1416

float *r)
void get_radius (float *r
{
main()
cout << "Please enter the radius: ";
{
cin >> *r;
float area, radius;
}
get_radius(&radius);
&radius
float *a, float rad)
void comp_area (float rad
&area , radius);
comp_area (&area, radius
{
cout << "\nThe area is " << area << ".";
*a = PI * rad * rad;
}
}

Pointers
MACHINE PROBLEMS

1. Write a program that will compute the capacitance of a spherical capacitor. The
formula is given as:

𝑎𝑏
𝑐𝑎𝑝𝑎𝑐𝑖𝑡𝑎𝑛𝑐𝑒 = 4𝜋𝜖0
𝑏−𝑎

where: π = 3.1416
0 = permittivity of free space = 8.85 x 10-12
a = radius of the inner conductor
b = radius of the outer conductor

The program starts by asking the user to enter the values for the inner and outer
radii of the conductors. The program will then compute and output the
capacitance. However, the program should ensure that the outer radius is
greater than the inner radius. If it's not, the program should inform the user
that invalid values were entered and ask the user to try again.

Pointers
MACHINE PROBLEMS

There should be a function to prompt the user to enter the outer and inner radii, a function to
compute the capacitance, and a function to print the results. All functions should directly
change the necessary variables in main(). N0 values should be returned.

The output of the program should follow the sample program run below:

Enter the radius of the inner conductor: 0.75


Enter the radius of the outer conductor: 0.50

Invalid values. Please try again.

Enter the radius of the inner conductor: 0.25


Enter the radius of the outer conductor: 0.50

The capacitance is 5.56063e-011 farads.

Use symbolic constants whenever necessary.

Pointers
MACHINE PROBLEMS

2. Write program that asks for your height in feet and inches and your weight in
pounds. (Use three variables to store the information). Have the program report
your body mass index (BMI).

To calculate the BMI, first convert your height in feet and inches to your height
in inches (1 foot = 12 inches).

Then, convert your height in inches to your height in meters by multiplying by


0.0254.

Then, convert your weight in pounds into your mass in kilograms by dividing by
2.2.

Finally, compute your BMI by dividing your mass in kilograms by the square of
your height in meters. Use symbolic constants to represent the various
conversion factors.

Pointers
MACHINE PROBLEMS

The output of the program should follow the sample


program run below:

Enter your height in feet and inches.


First, enter the feet: 5
Next, enter the inches: 5
Finally, enter your weight in pounds: 165

Your height in meters is 1.651.


Your weight in kilograms is 75.
Your BMI is 27.5148.

Pointers
MACHINE PROBLEMS

Use a function for each of the following:

A. Prompt the user to enter the necessary input data.


B. Converting the height in feet and inches to the height in
inches only.
C. Converting the height in inches to meters.
D. Converting the weight to kilograms.
E. Computing the BMI.
F. Print the results.

The functions should have no return values. Instead, they should


modify directly the variables of the calling program.

Pointers
MACHINE PROBLEMS

3. An hourly employee is paid a rate of 500 pesos per hour for up to 40 hours
worked per week. Any hours over that are paid at the overtime rate of 1.5 times
that.

From the worker’s gross or total pay, 1.5% is withheld or deducted for social
security tax, 3% is withheld for home development mutual fund (HDMF)
contribution, and 10% is withheld for professional income tax.

If the worker has three or more covered dependents, an additional 300 pesos is
withheld to cover the extra cost of health insurance beyond that paid by the
employer.

Write a C++ program that takes as input the number of hours worked in a week
and the number of dependents and then outputs the workers gross pay, each
withholding, and the net take home pay for the week.

Pointers
MACHINE PROBLEMS

The output of the program should follow the sample program run
below:

Enter the number of hours worked this week: 45


Enter the number of dependents: 4

Gross Pay = 23750 pesos

Social Security Tax = 356.25 pesos


HDMF = 712.5 pesos
Professional Income Tax = 2375 pesos
Health Insurance = 300 pesos

Net Take Home Pay for the Week = 20006.2 pesos

Pointers
MACHINE PROBLEMS

Use a function for each of the following:

A. Prompting the user to input the necessary data.


B. Computing the gross pay.
C. Computing the social security tax.
D. Computing for the HDMF contribution.
E. Computing for the professional income tax.
F. Computing for the health insurance.
G. Computing the net pay.

The functions should have no return values. Instead, they should


modify directly the variables of the calling program.

Pointers
POINTER ARITHMETIC
p
• A program can only use two arithmetic
operations on pointers: addition and 1,000
subtraction. However, these operators memory cells 1,001
work differently with pointers. allocated to
1,002 p = 1,000
variable x
Example: 1,003
1,004
Assume an integer variable x which is 1,005
currently occupying locations 1,000,
1,001, 1,002, and 1,003 in memory. 1,006
Assume also there is an int pointer p. 1,007
1,008
If the following statement is executed: 1,009
1,010
p = &x;
1,011
the pointer p will now point to x. 1,012
1,013
Since p is pointing to x, then p contains 1,014
1,000 (the address of the first memory
location of x). 1,015

Pointers
POINTER ARITHMETIC
p
Executing the statement ++p; 1,000
does not mean that p will memory cells 1,001
become equal to 1,001. allocated to p = 1,000
variable x 1,002
1,003 p
The statement ++p; is interpreted 1,004
memory cells
as p pointing to the next integer allocated to 1,005
location (which starts at 1,004). the next int 1,006 p = 1,004
variable (if
any) 1,007
There may not be an actual
integer occupying those 1,008
locations. C++ will assume there 1,009
is. 1,010
1,011
So after executing ++p, the new 1,012
value of p will be 1,004. This 1,013
means that p no longer points to 1,014
x.
1,015

Pointers
POINTER ARITHMETIC
p
1,000
memory cells 1,001
allocated to p = 1,000
variable x 1,002
1,003
1,004
If p = p + 3 was executed, then p 1,005
will point to the third integer from 1 1,006
where p is currently pointing. 1,007
1,008
So p will point to the integer 1,009
starting at memory location 1,012. 2 1,010
1,011 p
1,012
1,013
3 1,014 p = 1,012
1,015

Pointers
POINTER ARITHMETIC
p
memory cells 996
allocated to 997
the previous
int variable (if 998 p = 996
any) 999 p
The statement --p will cause p to 1,000
point to the previous integer memory cells 1,001
location. allocated to p = 1,000
variable x 1,002
1,003
This means p will become equal to 1,004
996, which is the address of the 1,005
first memory location of the
previous integer variable. 1,006
1,007
1,008
1,009
1,010
1,011

Pointers
POINTERS AND ARRAYS

• In C++, there is a close list


relationship between arrays
and pointers. list[0]
• When an array is declared list[1]
as:
list[2]
int list [10];
.
.
there is also a pointer called .
list (name of the array
without the index) that list[8]
automatically points to the
first element of the array. list[9]

Pointers
POINTERS AND ARRAYS

• It should be emphasized list


that the pointer list is fixed list[0]
(constant).
list[1]
• It cannot be changed to
point to another element by list[2]
using pointer arithmetic. .
.
For example, executing the
statement ++list will not .
make it point to the next list[8]
element of the array. It will
result in a compiler error. list[9]

Pointers
POINTERS AND ARRAYS

Take note that *list refers to list


the first element.
list[0]
The program may also use
*(list + 0) to access the first list[1]
element.
list[2]
The reference *(list + 1)
.
refers to the contents of the .
2nd element or list[1].
.
Similarly, *(list + 2) refers to list[8]
the contents of the 3rd
element or list[2]. list[9]

Pointers
POINTERS AND ARRAYS
list
list[0] 2
list[1] 4
• Sample Program 1
list[2] 6
#include <iostream>
using namespace std;
list[3] 8
list[4] 10
main()
{
int list[5] = {2, 4, 6, 8, 10};

cout << "\nThe 1st element of the array is " << *(list + 0);

cout << "\nThe 2nd element of the array is " << *(list + 1);
for (i = 0; i <= 4; ++ i)
cout << "\nThe 3rd element of the array is " << *(list
*(list ++ 2);
2); cout << "Element " << i + 1 << " is " << *(list +
i);
cout << "\nThe 4th element of the array is " << *(list + 3);

cout << "\nThe 5th element of the array is " << *(list + 4);
}

Pointers
POINTERS AND ARRAYS

• Suppose the following: list


list[0]
int list [10];
int *p; list[1] p

p = list; list[2]
.
Pointer p is now equal to . This can also
the address of the first
element of array name . be done by:
(pointing to the same thing list[8]
being pointed to by list
which is list[0]). p = &list[0];
list[9]

Pointers
POINTERS AND ARRAYS

Since the pointer p is p


a different pointer as list[0]
compared to the
pointer list, pointer list[1]
arithmetic can now list[2]
be applied to it. .
.
So executing ++p will .
make it point to the
next element of the list[8]
array list. list[9]

Pointers
POINTERS AND ARRAYS

p
Pointer arithmetic may now be
used to process the array. For list[0]
example, to add 2 to all
numbers in the array: list[1]
list[2]
for (p
p = list;
list ; p <= &list[9];
&list[9]; ++p)
++p .
*p = *p + 2;
.
Processing arrays using .
pointer arithmetic is generally list[8]
faster than using array
indexing. list[9]

Pointers
POINTERS AND ARRAYS

• Sample Program on Array Indexing (convert all letters in a string to uppercase):

#include <iostream> name[0] M


using namespace std; name[1] i
name[2] t
main()
name[3] c
{
char name[50]; int index; name[4] h
name[5] \0
cout << "Enter a string in lower case letters: "; name[6]
cin.get(name, 50);
.
.
for (index
index = 0;
0; name[index] != '\0';
'\0' ;++index)
++index
.
name[index] = toupper(name[index]);
name[48]
cout << "\nThe string in upper case letters is " << name; name[49]
}

Pointers
POINTERS AND ARRAYS

• Sample Program on Pointer Arithmetic (convert all letters in a string to uppercase): : name

#include <iostream> name[0] M p


using namespace std; name[1] i
name[2] t
main()
name[3] c
{
char name[50], *p; name[4] h
name[5] \0
cout << "Enter a string in lower case letters: "; name[6]
cin.get(name, 50);
.
.
p = name; *p != '\0';
for (p '\0'; ++p)
++p
.
*p = toupper (*p);
name[48]
cout << "\nThe string in upper case letters is " << name; name[49]
}

Pointers
INDEXING POINTERS

• Because of the close relationship between arrays and pointers, a


pointer can also be indexed as if it were an array.

Example:

int list[10];
int *p;

p = list;

at this point of the program, p[2] refers to the 3rd element of the
character array list. p[2] is the same as *(p + 2).

Pointers
INDEXING POINTERS

• Sample Program on Pointer Indexing:

#include <iostream>
using namespace std;

main()
{
char name[50];
char *p; int index;

cout << "Enter a string in lower case letters: ";


cin.get(name, 50);

p = name;
for (index = 0; p[index] != '\0'; ++index)
p[index] = toupper (p[index]);

cout << "\nThe string in upper case letters is " << name;
}

Pointers
MACHINE PROBLEMS

4. Write a C++ program that will prompt the user to enter 10


integers. The program should count all odd numbers and print
the results (use a function to do the counting). The program
should keep on repeating this until the user tells otherwise. Use
pointers and pointer arithmetic instead of array indexing.

The output of the program should follow the sample program run
below:

Enter integer 1: 4
Enter integer 2: 6
Enter integer 3: 5
Enter integer 4: 7
Enter integer 5: 8

Pointers
MACHINE PROBLEMS

Enter integer 6: 11


Enter integer 7: 10
Enter integer 8: 3
Enter integer 9: 18
Enter integer 10: 9

There are 5 odd numbers.

Do you want to try again?


Enter Y for Yes and N for No: N

Thank you for using this program.


Program Terminating!

Pointers
MACHINE PROBLEMS

5. Write a C++ program that will prompt the user to enter a


string (maximum of 100 characters). The program should
then print the reverse of the string. Use a function to do
this. Use pointers and pointer arithmetic instead of array
indexing.

The output of the program should follow the sample


program run below:

Please enter a string: Mitch Andaya

The reverse of the string is ayadnA hctiM

Pointers
MACHINE PROBLEMS

6. Write a C++ program that will prompt the user to enter a


string (maximum of 100 characters). The program should
then capitalize the first letter in every word of a string
parameter. All other letters should be in lowercase. Use a
function to do this. Use pointers and pointer arithmetic
instead of array indexing.

The output of the program should follow the sample


program run below:

Please enter a string: mitCh anDaya

The revised string is Mitch Andaya.

Pointers
POINTERS AND STRINGS

• It is possible to assign the address of a specific element of an array. This is


achieved by using the & operator to an index array.

Example:

char name[50];
char *p

p = &name[6];

The pointer variable p now points to the 7th element of the character array
name. This technique is particularly useful in handling substrings.

If cout << p is executed, it will print the substring starting from the 7th character
up to last character (the one preceding the NULL character).

Pointers
INDEXING POINTERS

• Sample Program on Substrings:

#include <iostream>
using namespace std;
The output of this program will be:
main()
{ Enter a string: Mitch Andaya 
char name[50]; The selected substring is Andaya
char *p;

cout << "Enter a string : ";


cin.get(name, 50);

p = &name[6];

cout << "\nThe substring selected is " << p;


}

Pointers

You might also like