0% found this document useful (0 votes)
209 views45 pages

CSC404 Chapter1

This document discusses pointers in C++. It begins by describing pointers as variables that store memory addresses and can be used to indirectly access the value of the variable located at that address. It then covers declaring and initializing pointer variables, using the * and & operators to dereference and get the address of variables, assigning pointers, and using pointers to refer to variables directly and indirectly. The document also introduces dynamic memory allocation using the new operator, which allocates memory at runtime and returns a pointer to that memory.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
209 views45 pages

CSC404 Chapter1

This document discusses pointers in C++. It begins by describing pointers as variables that store memory addresses and can be used to indirectly access the value of the variable located at that address. It then covers declaring and initializing pointer variables, using the * and & operators to dereference and get the address of variables, assigning pointers, and using pointers to refer to variables directly and indirectly. The document also introduces dynamic memory allocation using the new operator, which allocates memory at runtime and returns a pointer to that memory.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

CHAPTER 1

Pointers
Learning Outcomes
— At the end of these lessons, students should be
able to:
— Describe the pointer data type and pointer
variables.
— Declare and manipulate pointer variables.
— Use pointer operators: address operator (&)
and dereferencing/indirection operator (*).
— Use the new and delete operators to
manipulate dynamic variables.
— Describe operations on pointer variables
What is Pointer?
— Pointer variables, simply called pointers, is a
variable whose content is an address (that is, a
memory address)
— Normally, a variable contains a specific value, e.g., an
integer, a floating-point value and a character.
— However, a pointer contains the memory address of a
variable that in turn contains a specific value.
pCount count

Address of variable Address of variable


Address of pCount 5
count count
Declaring Pointer Variables

— Pointers must be declared before they can be used to


store an address.
— Syntax:

data_type *pointer_variable_name;

— Each variable being declared as a pointer must be


preceded by an asterisk (*).
Declaring Pointer Variables (Cont.)
— Example:
double *pCount;

— pCount is declared a “pointer to double” variable


— Can hold pointers to variables of type double
— Not other types!
— Pointers can be declared along with non-pointer variables.
int *p1, *p2, v1, v2;

— p1, p2 hold pointers to int variables.


— v1, v2 are ordinary int variables.
Declaring Pointer Variables (Cont.)
— Note the position of the *, it is valid for all the three
positions:
int *p;
int* p; These statements are equivalent
int * p;

Pointer Data Type Pointer Variable


§ Allows us to designate a § Variable that holds the
variable to hold an address address of a memory
or a pointer.
Pointer Type
— A pointer variable is declared with a type such as int,
double, etc.
— You have to assign the address of the variable of the same
type.
— It is a syntax error if the type of the variable does not match
the type of the pointer.
— For example, the following code is wrong:
int area = 1;
double *pArea = &area;
Initializing Pointer
— Once a pointer is declared, we must initialize the pointer,
that is, make the pointer point to something.
— Syntax:
Pointer_variable_name = initial_value;
— A pointer can be initialized when it is declared or by using an
assignment statement.
— A pointer may be initialized to 0 or NULL, which is a
special value for a pointer to indicate that the pointer points
to nothing.
Example Initializing Pointer
— char* x = NULL;
— Create a pointer named x and initialize it to NULL; the pointer can store
the address of a char variable.

— int *type_of_car = NULL;


— Create a pointer named type_of_car and initialize it to NULL; the
pointer can store the address of a int variable.

— float *value;
value = NULL;
— Create a pointer named value and initialize it to NULL; the pointer can
store the address of a float variable.
The * and & Operators
— The * operator:
— In front of a pointer variable
— An unary operator that returns the value of the variable
located at the address that follows – get data that pointer
variable points to
— Also known as the dereferencing operator or indirection
operator
— The & operator:
— In front of an ordinary variable
— An unary operator that returns the memory address of its
operand/variable – determines “address of ” variable
— Also known as the address-of-operator
Cont…
— For example, consider the declarations,
double *p, v;

The following sets the value of p so that p points to the


variable v:
p = &v;

*p return the value of variable pointed to by p, so after the


above assignment, *p and v refer to the same variable. For
example, the following sets the value of v to 9.99.
*p = 9.99;
Cont…
double *p, v;
p v
?

p = &v;
p v p v
? ? 2000 ?
2000
*p = 9.99;
p v
9.99
Referring to a Variable
— Recall:
double *p, v;
p = &v;

— Two ways to refer to v now:


— Direct referencing: the statement uses the variable’s name to
directly access its contents
— Variable v itself:
cout << v;
cin >> v;
v = 200;
Referring to a Variable

— Indirect referencing: the statement uses the address stored in


its associated pointer
— Via pointer p:

cout << *p;


cin >> *p;
*p = 200;
Pointer Assignment
— Pointer variables can be “assigned”:
int *p1, *p2;
p1 = p2;
— Assigns one pointer to another
— “make p1 point to where p2 points”

p1 = p2;
Before After
p1 8 p1 8

p2 9 p2 9
Cont…
— Do not confuse with:
*p1 = *p2;
— Assigns “value pointed to” by p1, to “value pointed to” by p2

*p1 = *p2;
Before After
p1 8 p1 9

p2 9 p2 9
Example
The value of count is 5
int main() The address of count is 0x0012ff50
{ The address of count is 0x0012ff50
int count = 5; The value of count is 5
int *pCount = NULL;
The address of pCount is 0x0012ff4c
pCount = &count;

cout<<“The value of count is ”<<count<<endl;


cout<<“The address of count is ”<<&count<<endl;
cout<<“The address of count is ”<<pCount<<endl;
cout<<“The value of count is ”<<*pCount<<endl;
cout<<“The address of pCount is ”<<&pCount<<endl;
}
Exercise 1

— Explain the meaning of each of the following declaration:

— int *a, *b, c;

— float *f;

— char *d, e;
Exercise 2
— What is the output produced by the following code?
int *p1, v1;
v1 = 0;
p1 = &v1;
*p1 = 42;
cout << v1 <<endl;
cout << *p1 <<endl;

— What is the output produced by the following code?


int x, y, *z;
x = 5;
z = &x;
y = *z + 9;
cout << y;
Cont…
— What is the output produced by the following code?
float f1, f2 = 25.0, *f3, *f4;
f3 = &f2;
cout << *f3 + 7.2;
f1 = 20.00;
f4 = &f1;
cout << *f3 + *f4;

— What is the output produced by the following code?


char name[20] = “abc”, *p;
p = name;
for(int i=0; i<3; i++)
cout << *(p+i);
Exercise 3
— For each of the following, write a statement that performs the
indicated task. Assume that floating point variables num1 and
num2 are defined and that num1 is initialized to 20.5.
— Define the variable numPtr to be a pointer to a variable of type
float.
— Assign the address of variable num1 to pointer variable numPtr.
— Print the value of the variable pointed to by numPtr.
— Assign the value of the variable pointed to by numPtr to variable
num2.
— Print the value of num2.
— Print the address of num1.
— Print the address stored in numPtr. Is the value printed the same as
the address of num1.
Exercise 4
— Write a program that creates the structure shown in figure below.
It then reads date into a, b, and c using the pointers p, q, and r.

p q r

a b c

— After the data have been read, the program reassigns the pointers
so that p points to c, q points to a and r points to b. after making
the reassignments, the program prints the variables using the
pointers. For each variable, print both its contents and its address.
Exercise 5

— Write a program that will add two numbers using pointers.


The output of the program is as below:

Enter the first number: 55


Enter the second number: 11

55 + 11 is 66
Dynamic Variable

Operator new & delete


Dynamic Variables

— Dynamic variables: created during execution


— C++ creates dynamic variables using pointers
— Two operators, new and delete, to create and destroy
dynamic variables
— new and delete are reserved words
— These two memory management operators are used for
allocating and freeing memory blocks in efficient and
convenient ways.
new Operator
— new has two forms:
new dataType; //to allocate a single variable
new dataType [intExp];//to allocate an array of variables

— Where intExp is any expression evaluating to a positive integer

— new allocates memory (a variable) of the designated type and


returns a pointer to it
— The address of the allocated memory
— Operator new creates variables
— No identifiers to refer to them
— Just a pointer!
Cont…
— The allocated memory is un-initialized
— Dynamic variables are never initialized by the compiler
— The assignment can be made in either of the two ways:

int *a = new int;


*a = 20;
or

int *a = new int(20);


Cont…
— The statement:
p = new int;

— Creates a variable during program execution somewhere in


memory, and stores the address of the allocated memory in p
— Creates new “nameless” variable and assigns p to “point to” it

— To access allocated memory: *p


Example *p1 == 42
*p2 == 42
int main() *p1 == 53
{ *p2 == 53
int *p1, *p2; *p1 == 88
*p2 == 53
p1 = new int; Hope you got the point of this example!
*p1 = 42;
p2 = p1;
cout<<“*p1 == ”<<*p1<<endl;
cout<<“*p2 == ”<<*p2<<endl;

*p2 = 53;
cout<<“*p1 == ”<<*p1<<endl;
cout<<“*p2 == ”<<*p2<<endl;

p1 = new int;
*p1 = 88;
cout<<“*p1 == ”<<*p1<<endl;
cout<<“*p2 == ”<<*p2<<endl;

cout<<“Hope you got the point of this example!\n”;


return 0;
}
Explanation
(a) (d)
int *p1, *p2; p2 = p1;

p1 ? p1
42
p2 ? p2

(b) (e) (g)


p1 = new int; *p2 = 53; *p1 = 88;
p1 p1 p1
53 88
?
p2 ? p2 p2
53
(f)
(c)
p1 = new int;
*p1 = 42;
p1
p1 ?
42 p2
p2 ?
53
Exercise 1
— What will be printed by the following program segment:

int *p, *q;


int x, y;

p = new int;
*p = 5;
x = *p + 1;
y = *p;
q = new int;
*q = y + 3;
cout<<x<<“ ”<<y<<“ ”<<*p<<“ ”<<*q<<endl;
Exercise 2
— What is the output for the following program segment:

int *p, *q, y = 8;


p = new int;
*p = 5;
q = &y;
y = 2;
p = q;
cout<<*p;
cout<<*q;
cout<<y;
Exercise 3
— What will be printed by the following program segment:

char ch = ‘p’;
int a=2, b=5;
int *ptra = &a, *ptrb = &b, *ptrc;
char *ptrch1 = &ch, *ptrch2;
cout<<*ptra<<“ ”<<*ptrb<<“ ”<<*ptrch1<<endl;
*ptra = a + 20;
ptrc = new int(99);
ptrb = ptrc;
*ptrc = *ptrb + 10;
ptrch2 = new char(‘h’);
ch = ‘y’;
cout<<*ptra<<“ ”<<*ptrb<<“ ”<<*ptrc<<endl;
cout<<*ptrch1<<“ ”<<*ptrch2<<endl;
Exercise 4
— Give the output from this code fragment:

int *p1, *p2;


p1 = new int;
p2 = new int;
*p1 = 10;
*p2 = 20;
cout<<*p1<<“ ”<<*p2<<endl;
*p1 = *p2;
cout<<*p1<<“ ”<<*p2<<endl;
*p1 = 30;
cout<<*p1<<“ ”<<*p2<<endl;
delete Operator

— The delete operator eliminates a dynamic variable and


returns the memory that the dynamic variable occupied to
the freestore (heap).
— The memory can then be reused to create new dynamic
variables.
Cont…
p = new int; (iii) p after the execution of p = new int;
1500
*p = 54; Memory leak
54
p = new int;
1800
*p = 73;
p 1800
(i) p after the execution of p = new int;
1500
(iv) p after the execution of p = 73;
p 1500
1500
54
(ii) p and q after the execution of *p=54;
1800
1500
p 1800 73
p 1500 54
Cont…
— To avoid memory leak (unreferenced memory space), when a
dynamic variable is no longer needed, destroy it
— De-allocate its memory
— When no longer needed
— Returns memory to freestore
— delete is used to destroy dynamic variables
— Syntax:
delete pointerVariable; //to deallocate a single
// dynamic variable
delete[] pointerVariable;//to deallocate a dynamically
//created array
Example
— Consider the following program segment:

int *p;
p = new int;
*p = 1234;
cout<<*p<<endl;
delete p;
cout<<*p<<endl;

— After p has been deleted, p still points to memory cell that has
been de-allocated and that is therefore supposed to be available for
other uses.
— A pointer such as this is known as a dangling pointer and can
be the cause of troublesome problem bugs.
Avoid Dangling Pointers

— After deleting a pointer variable, you should assign NULL


pointer to that variable.
— Assign pointer to NULL after delete:

delete p;
p = NULL;
Operations on Pointer Variables
Pointer Operations (1 of 4)
— Assignment
— Value of one pointer variable can be assigned to another pointer
of same type.
— Example:
int *p, *q;
p = q;

• This statement copies the value of q into p.


• After this statement executes, both p and q point to the same
memory location.
• Any changes made to *p automatically change the value of
*q, and vice versa.
Pointer Operations (2 of 4)
— Relational operations
— Two pointers variables of same type can be compared for
equality, etc.
— For example:
p == q
This expression evaluates to true if p and q have the same
value – that is , if they point to the same memory location.

p != q
This expression evaluates to true if p and q point to
different memory location.
Pointer Operations (3 of 4)
— Some limited arithmetic operations
— Here is an example of pointer declarations:

int *p;
double *q;
char *chPtr;
p++; // or p=p+1;
These statements increment the value of p by 4 bytes because p is a
pointer of type int.

q++;
chPtr++;
These statements increment the value of q by 8 bytes and the value of
chPtr by 1 byte, respectively.
Pointer Operations (4 of 4)
p = p + 2;
These statements increment the value of p by 8 bytes.

When an integer is added to a pointer variable, the value of the


pointer variable incremented by the integer times the size of the
memory that the pointer is pointing to.

When an integer is subtracted from a pointer variable, the value


of the pointer variable is decremented by the integer times the
size of the memory to which the pointer is pointing.
END OF CHAPTER 1

You might also like