[go: up one dir, main page]

0% found this document useful (0 votes)
6 views18 pages

PF Lecture 11a

Uploaded by

i246509
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views18 pages

PF Lecture 11a

Uploaded by

i246509
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Programming

Fundamentals
Lecture 11a
Pointer to Constants
• Sometimes it is necessary to pass the address of a const item into a pointer.
• When this is the case, the pointer must be defined as a pointer to a const item.
• For example, consider the following array definition:
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 const doubles.
• This means that each element in the array is a const double, and the compiler
will not allow us to write code that changes the array’s contents.
• If we want to pass the payRates array into a pointer parameter, the parameter
must be declared as a pointer to const double.
Pointer to Constants
void displayPayRates(const double *rates, int size)
{
// Set numeric output formatting.
cout << setprecision(2) << fixed << showpoint;
// Display all the pay rates.
for (int count = 0; count < size; count++)
{
cout << “Pay rate for employee ” << (count + 1)
<< “ is $" << *(rates + count) << endl;
}
}
Pointer to Constants
• Because rates is a pointer to a const, the compiler will not allow us to write code
that changes the thing that rates points to. (using the dereference operator,
value of rate can't be changed).
• In passing the address of a constant into a pointer variable, the variable must be
defined as a pointer to a constant.
• Pointer to const is still a variable, but it is pointer to a constant.
• If the word const had been left out of the definition of the rates parameter, a
compiler error would have resulted.
• Although a constant’s address can be passed only to a pointer to const, a pointer
to const can also receive the address of a nonconstant item.
Example void displayValues(const
This program demonstrates a pointer to int *numbers, int size)
const parameter {
#include <iostream> for (int count = 0; count
using namespace std;
void displayValues(const int *, int); < size; count++)
int main() {
{ cout << *(numbers +
const int SIZE = 6; count) << " ";
const int array1[SIZE] = { 1, 2, 3, 4,
5, 6 }; }
int array2[SIZE] = { 2, 4, 6, 8, 10, cout << endl;
12 }; }
displayValues(array1, SIZE);
displayValues(array2, SIZE);
return 0;
}
Constant Pointer
• You can also use the const key word to define a constant pointer.
• Here is the difference between a pointer to const and a const pointer:
 A pointer to const points to a constant item. The data that the pointer
points to cannot change, but the pointer itself can change.
 With a const pointer, it is the pointer itself that is constant. Once the
pointer is initialized with an address, it cannot point to anything else.
• The following code shows an example of a const pointer.
int value = 22;
int * const ptr = &value;
• Notice in the definition of ptr the word const appears after the asterisk. This
means that ptr is a const pointer
Constant Pointer
• In the code, ptr is initialized with the address of the value variable.
• Because ptr is a constant pointer, a compiler error will result if we write code
that makes ptr point to anything else.
• An error will not result, however, if we use ptr to change the contents of value
(dereferencing).
• This is because value is not constant, and ptr is not a pointer to const.
Constant Pointer
• Constant pointers must be initialized with a starting value.
• If a constant pointer is used as a function parameter, the parameter will be
initialized with the address that is passed as an argument into it and cannot be
changed to point to anything else while the function is executing.
• Here is an example that attempts to violate this rule:
void setToZero(int * const ptr)
{
ptr = 0; // ERROR!! Cannot change the contents of ptr.
}
void setToZero(int * const ptr)
{
*ptr = 0; // This will compile as the pointe is not const.
}
Constant Pointer to
Constants
• You can also have constant pointers to constants. For example, look at the
following code:
int value = 22;
const int * const ptr = &value;
• In this code ptr is a const pointer to a const int.
• Notice the word const appears before int, indicating that ptr points to a const
int, and it appears after the asterisk, indicating that ptr is a constant pointer.
Pointer to String Constants
• Here’s an example, TWOSTR, in which two strings are defined, one using array notation and one using
pointer notation:
#include <iostream>
using namespace std;
int main()
{
char str1[ ] = “Defined as an array”;
char* str2 = “Defined as a pointer”;
cout << str1 << endl; // display both strings
cout << str2 << endl;
// str1++; // can’t do this; str1 is a constant (name of array)
str2++; // this is OK, str2 is a pointer
cout << str2 << endl; // now str2 starts “efined...”
return 0;
}
String Copy Using Poiners
// copies one string to another with void copystr(char* dest,
pointers
#include <iostream> const char* src)
using namespace std; {
void copystr(char*, const char*); while( *src ) //until null
//prototype character,
int main()
{ *dest++ = *src++; //copy
char* str1 = “Self-conquest is the chars from src to dest
greatest victory.”; *dest = ‘\0’; //terminate
char str2[80]; //empty string
copystr(str2, str1); //copy str1 to
dest
str2 }
cout << str2 << endl; //display str2
return 0;
}
Arrays of Pointers to Strings
// an array of pointers to strings
#include <iostream>
using namespace std;
const int DAYS = 7; //number of pointers in array
int main()
{
char* arrptrs[DAYS] = { “Sunday”, “Monday”, “Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday” };
for(int j=0; j<DAYS; j++) //display every string
cout << arrptrs[j] << endl;
return 0;
}
Memory Management (Dynamic
Memory Allocation)
• Dynamic memory allocation means allocate memory to a variable at run time.
• To dynamically allocate memory means that a program, while running, asks the
computer to set aside a chunk of unused memory large enough to hold a
variable of a specific data type.
• Dynamic memory allocation is only possible through use of pointers.
• Let’s say a program needs to create an integer variable. It will make a request to
the
• computer that it allocate enough bytes to store an int.
• When the computer fills this request, it finds and sets aside a chunk of unused
memory large enough for the variable.
• It then gives the program the starting address of the chunk of memory.
• The program can only access the newly allocated memory through its address,
so a pointer is required to use those bytes.
Memory Management (Dynamic
Memory Allocation)
• The way a C++ program requests dynamically allocated memory is through the
new operator.
• Assume a program has a pointer to an int defined as
int *iptr = nullptr;
• Here is an example of how this pointer may be used with the new operator:
iptr = new int;
• This statement is requesting that the computer allocate enough memory for a
new int variable.
• The operand of the new operator is the data type of the variable being created.
Once the statement executes, iptr will contain the address of the newly
allocated memory.
Memory Management (Dynamic
Memory Allocation)
int *iptr = nullptr;
iptr = new int;
*iptr = 25; // A value may be stored in this new variable by
dereferencing the pointer:

cout << *iptr; // Display the contents of the new variable.

cin >> *iptr; // Let the user input a value.

total += *iptr; // Use the new variable in a computation.


Memory Management (Dynamic Memory Allocation)
Memory Management (Dynamic
Memory Allocation)
• A more practical use of the new operator is t0 dynamically create
an array.
• Here is an example of how a 100-element array of integers
may be allocated:
iptr = new int[100];
• Once the array is created, the pointer may be used with subscript notation to
access it.
• For instance, the following loop could be used to store the value 1 in each
element:
for (int count = 0; count < 100; count++)
iptr[count] = 1;
Memory Management (Dynamic
Memory Allocation)
• But what if there isn’t enough free memory to accommodate the request?
• What if the program asks for a chunk large enough to hold a 100,000-element
array of floats, and that much memory isn’t available?
• When memory cannot be dynamically allocated, C++ throws an exception and
terminates the program.
• Throwing an exception means the program signals that an error has
occurred.
• When a program is finished using a dynamically allocated chunk of memory, it should
• release it for future use.
• The delete operator is used to free memory that was allocated with new.
• Here is an example of how delete is used to free a single variable, pointed to by iptr:
delete iptr;
• If iptr points to a dynamically allocated array, the [ ] symbol must be placed between delete and
iptr:
delete [ ] iptr;

You might also like