SlideShare a Scribd company logo
Declaring a Pointer
To define a pointer, use an asterisk, (*), in the declaration to specify the variable will be a pointer
to the specified data type.
Recall that the name of an array holds the memory address of the first element of the array. The
second statement then would store the memory address of the first value in the variable valuePtr.
The name of a pointer is an identifier and must follow the rules for defining an identifier. Some
programmers place the letters ptr, a common abbreviation for pointer, at the end of the variable
name, others prefix a pointer with p_ or ptr_, and there are those who do nothing to distinguish a
pointer by its name. The naming of a pointer variable is a matter of programming style.
Once a pointer has been declared and initialized, it can be used to access the data to which it
points. In order to access this value, the dereference operator, *, must be used to prefix the name
of the pointer. From the code above, valuePtr holds the address of the first element of the values
array; therefore, *valuePtr will access the value 325. Add the following to main and execute the
program.
The output generated should look something like the following.
Where 0xbfad43e8 is a memory address displayed in hexadecimal.
Obtaining the Memory Address of a Variable
The address operator, &, is used to determine the memory address of a variable that is not an
array. Add code necessary to use fixed and setprecision, then add the following to main and run
the program to confirm the use of the address operator.
Using a Pointer to Alter Data
Just as the dereference operator is used to retrieve data, so too is it used to store data. Add the
following to function main and run the program.
The pointer, ratePtr, is used to change the data stored in payRate. The output of payRate
confirms the change.
Using a Pointer in an Expression
As previously shown, the value pointed to by a pointer variable can be retrieved by dereferencing
the pointer. In the above code, the retrieved value was simply displayed to the screen; however,
it can also be used in an expression. Add the following to main and execute the program.
Pointer Arithmetic
It is possible to add to or subtract from a memory address stored in a pointer. These actions can
be accomplished using the addition operator,+, subtraction operator, - and the increment and
decrement operators, ++ and --. This is helpful when accessing arrays via pointers.
The increment operator has been used to add the value 1 to a variable. When used with a pointer,
the increment operator adds the size of the data referenced to the memory address stored in the
pointer, effectively moving the pointer to the next data value. Building on the code from above,
add the following to main and execute the program.
We initialized valuePtr to the memory address of the first element of the array values.
Incrementing valuePtr instructs the computer to add four bytes, the size of an integer, to the
memory addressed stored in valuePtr. After the increment, valuePtr now points to the second
element of the array.
The addition operator, +, works in a similar fashion. Add the following to function main and
execute the program.
Note that the value stored in valuePtr is not modified by this code. valuePtr currently points to
the second element in the array. The program interprets the instruction to add two, *(valuePtr +
2), as add two times the size of an integer to the contents of valuePtr and access that address; this
would be the fourth element of the array. The next line of code allows the confirmation of the
interpretation of the addition by displaying the value in the fourth element of the array.
The last line of code is included to demonstrate the need for the parenthesis when using the
dereference operator when using the addition operator to alter the memory address. Add code to
test the necessity of using parenthesis with the increment operator.
The subtraction and decrement operators perform in a similar manner.
Pointers as Parameters
As with any other variable, pointers may be passed to functions as parameters. In a previous lab,
a memory addressed was passed to a function using a reference parameter. The idea here is the
same, only the syntax has changed.
A pointer parameter is specified using the same syntax as a pointer declaration. Within the
function itself, the pointer is used as before; the name of the pointer holds the memory address
and the data can be accessed by dereferencing the pointer.
Add the following function to the program.
The function call must match the function definition. The function definition has specified that
the function expects a memory address; the function call must therefore send the function a
memory address. Add the following to main and execute the program.
Because the pointer is a memory address, changes to the data value within the function will be
seen outside the function.
When passing an array via a pointer, the data values can be accessed using array notation or
pointer notation. Add the following to the program.
Add the following to function main and execute the program.
The name of an array holds the memory address of the first element of the array; therefore, the
name of an array is essentially a pointer to the first element of the array. Recall that the index
specified within the [] operator, in array notation, instructs the computer to move that many
elements from the first element. The computer calculates the distance to move using the same
method as pointer arithmetic; the index value is multiplied by the size of the data type to
determine the distance to move from the memory address of the first element.
Just to help you practice with pointer math, replace the previous array notation version of
displayArray with the following pointer notation version and execute the program.
One final array notation option exists for the displayArray function. While an array name's value
cannot change, a pointer's value can change. When an array is declared, the name of the array
holds the memory address of the first element. If this value could be changed, there would be no
way to retrieve the original memory address and data would be lost. The name of an array is a
constant pointer. The pointer itself cannot change. When passing an array to a function, the
memory address is passed to a pointer; this pointer is not a constant pointer and can be changed.
There is no danger in changing the pointer's value (or memory address) in the function as the
name of the array, in the calling function, still holds the original memory address. Replace the
previous pointer notation version of displayArray with the following pointer notation version and
execute the program.
Dynamic Memory Allocation
A variable declaration reserves memory for a variable. The amount of memory to be reserved
must be known by the programmer. However, there are instances when the programmer may not
know the exact amount of memory that will be needed by those that will use the program. As an
example, recall from a previous lab the declaration of an array to store student scores. As the
number of students was unknown, the array was declared large enough to store scores for double
the largest expected class size. This approach works well until the assumption of the expected
class size is no longer valid.
A better approach might be to reserve the amount of memory needed at the time of the
program's execution. In this example, that would require the program to first determine the
number of students in the class, and then reserve that amount of memory. However, when
declaring an array, the size must be an integer constant or literal; it cannot be a variable.
The new Operator
The new operator allows the program to dynamically, at run-time, reserve memory. The new
operator has one operand on its right which specifies the amount, or size, of memory to allocate.
The new operator returns the memory address of the allocated memory.
Where size_to_allocate is typically a data type and pointerName has been declared a pointer of
that type.
Once allocated, the memory can be accessed via the pointer as discussed previously. It is
important to note that memory allocated in this way is not initialized just as local variables are
not. Be sure to initialize the memory before accessing it in an expression.
The delete Operator
Once memory has been allocated using new, the memory is accessible until it is released using
the delete operator. The delete operator releases any memory obtained by new so that it can be
used for other purposes either later in the program or by another process running concurrently on
the computer.
Add the following to function main and execute the program.
delete must never be used to release any memory not obtained via new. The address nullptr is
reserved so that any attempt to dereference a pointer to that address will fail. You should always
set an owning pointer to nullptr after freeing the memory that it was managing, since the address
of that (now deallocated) memory is still stored in the pointer; leaving it intact opens you to the
possibility of accidentally making use of a storage location that no longer belongs to your
program.
new[] and delete[]
Use the [] operator in conjunction with new to dynamically allocate an array.
Where arrayName has been declared a pointer to the specified data type. This instruction will
allocate size_of_array many elements of data_type. As with any array, the elements will occupy
consecutive memory addresses. As with any locally declared variable, the memory is not
initialized.
Use the [] operator in conjunction with delete to release any memory allocated with the new[]
operator.
Add the following to the program.
Add the following to function main and execute the program.
This code will reserve enough consecutive space in memory to store ten integers and the address
of the first element will be stored in the pointer variable moreValues.
While this code will dynamically allocate memory for the array, the literal 10 in the code still
forces the programmer to determine the amount of memory needed prior to execution of the
program. With new the programmer is no longer constrained to use a constant or literal to
specify the size of the array. Replace the previous code in main with the following and execute
the program.
With this code, the programmer is no longer forced to decided memory usage prior to the
program's execution. Here, the user specifies the number of elements that will be needed; that
amount of memory and only that amount of memory is reserved.
Memory allocated using new remains available until it is released. delete need not be used within
the function using new. To demonstrate, modify the getData function as follows.
Then modify main as follows and execute the program.Code Illustration
Solution
solution
#include
#include
using namespace std;
int main()
{
int values[5] = {325, 879, 120, 459, 735};
int *valuePtr = values;
cout<<"the expected output"<
#include
#include
using namespace std;
int main()
{
double payRate = 7.25;
double *ratePtr = &payRate;
cout << fixed << setprecision(2);
cout << "address of payRate: " << ratePtr << endl;
cout << "data store in payRate: " << *ratePtr << endl << endl;
}
output
address of payRate: 0x22fe30
data store in payRate: 7.25
//use pointer to alter the data
#include
#include
#include
using namespace std;
int main()
{
double payRate = 7.25;
double *ratePtr = &payRate;
cout << fixed << setprecision(2);
cout << "address of payRate: " << ratePtr << endl;
cout << "data store in payRate: " << *ratePtr << endl << endl;
*ratePtr = 10.50;
cout << "altered value of payRate: " << payRate << endl << endl;
}
output
address of payRate: 0x22fe30
data store in payRate: 7.25
altered value of payRate: 10.50
//array values
#include
#include
#include
using namespace std;
void displayArray(int *array, int size)
{
cout << "Array values:  ";
for (int i=0; i < size; i++)
cout << array[i] << endl;
cout << endl;
}
int main()
{
int values[]={1,2,3,4,5} ;
displayArray(values,5);
}
output
array values
1
2
3
4
5
//array values
#include
#include
#include
using namespace std;
void displayArray(int *array, int size)
{
cout << "Array values:  ";
for (int i=0; i < size; i++)
cout << *(array + i) << endl;
cout << endl;
}
int main()
{
int values[]={1,2,3,4,5} ;
displayArray(values,5);
}
output
Array values:
1
2
3
4
5
//allocate the size dynamically
#include
#include
#include
using namespace std;
void displayArray(int *array, int size)
{
cout << "Array values:  ";
for (int i=0; i < size; i++,array++) // "moves" the pointer
cout << *array << endl;
cout << endl;
}
int main()
{
//int values[]={1,2,3,4,5} ;
int* values = NULL; // Pointer to int, initialize to nothing.
int n;
cout<<"enter the size needed for array"<> n; // Read in the size
values = new int[n]; // Allocate n ints and save ptr in a.
for (int i=0; i
int main()
{
double *dv = new double;
*dv = 88.25;
cout << "address of dv: " << dv << endl;
cout << "value of dv: " << *dv << endl << endl;
delete dv;
dv = NULL; // NULL the pointer so that it cannot accidentally be dereferenced again.
}
output
address of dv: 0x537410
value of dv: 88.25
0
//program
#include
#include
#include
using namespace std;
void displayArray(int *array, int size)
{
cout << "Array values:  ";
for (int i=0; i < size; i++,array++) // "moves" the pointer
cout << *array << endl;
cout << endl;
}
void getData (int *array, int size)
{
for (int i=0; i> array[i];
}
}
int main()
{
int *moreValues = new int[10];
getData(moreValues,10);
displayArray(moreValues,10);
delete [] moreValues;
}
output
Enter value 2: 2
Enter value 3: 3
Enter value 4: 4
Enter value 5: 5
Enter value 6: 6
Enter value 7: 7
Enter value 8: 8
Enter value 9: 9
Enter value 10: 10
Array values:
0
2
3
4
5
6
7
8
9
10
//program
#include
#include
#include
using namespace std;
void displayArray(int *array, int size)
{
cout << "Array values:  ";
for (int i=0; i < size; i++,array++) // "moves" the pointer
cout << *array << endl;
cout << endl;
}
void getData (int *array, int size)
{
for (int i=0; i> array[i];
}
}
int main()
{
int numberOfMoreValues;
cout << "How many more values would you like to enter? ";
cin >> numberOfMoreValues;
int *moreValues = new int[numberOfMoreValues];
getData(moreValues,numberOfMoreValues);
displayArray(moreValues,numberOfMoreValues);
delete [] moreValues;
moreValues =NULL; // NULL the pointer for safety.
}
output
How many more values would you like to enter? 10
Enter value 1: 1
Enter value 2: 2
Enter value 3: 3
Enter value 4: 4
Enter value 5: 5
Enter value 6: 6
Enter value 7: 7
Enter value 8: 8
Enter value 9: 9
Enter value 10: 10
Array values:
1
2
3
4
5
6
7
8
9
10
//program
#include
#include
#include
using namespace std;
void displayArray(int *array, int size)
{
cout << "Array values:  ";
for (int i=0; i < size; i++,array++) // "moves" the pointer
cout << *array << endl;
cout << endl;
}
int *getData (int &numberOfMoreValues)
{
cout << "How many more values would you like to enter? ";
cin >> numberOfMoreValues;
int *dynamicArray = new int[numberOfMoreValues];
for (int i=0; i> dynamicArray[i];
}
return dynamicArray;
}
int main()
{
int numberOfMoreValues;
int *moreValues = getData(numberOfMoreValues);
displayArray(moreValues,numberOfMoreValues);
delete [] moreValues;
moreValues = NULL; // NULL the pointer for safety.
}
output
How many more values would you like to enter? 5
Enter value 1: 20
Enter value 2: 30
Enter value 3: 40
Enter value 4: 50
Enter value 5: 60
Array values:
20
30
40
50
60

More Related Content

PPTX
Pointers in c language
PPTX
Pointers in c v5 12102017 1
PPTX
C++ - UNIT_-_IV.pptx which contains details about Pointers
PDF
C_Program_Yr1[1].pdf for computer science
PPTX
ADK COLEGE.pptx
PPTX
C++.pptx
PDF
PROBLEM SOLVING USING PPSC- UNIT -4.pdf
PPT
Pointers (Pp Tminimizer)
Pointers in c language
Pointers in c v5 12102017 1
C++ - UNIT_-_IV.pptx which contains details about Pointers
C_Program_Yr1[1].pdf for computer science
ADK COLEGE.pptx
C++.pptx
PROBLEM SOLVING USING PPSC- UNIT -4.pdf
Pointers (Pp Tminimizer)

Similar to Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdf (20)

PDF
1-Intoduction ------------- Array in C++
PPTX
Function Overloading Call by value and call by reference
PDF
C Programming - Refresher - Part II
PPTX
Unit 3(Arrays).pptx arrays topics in the c lang
PPT
Lecture 8
PPTX
data structures using C 2 sem BCA univeristy of mysore
PDF
Pointers in c++
PPTX
c++ arrays and pointers grade 9 STEP curriculum.pptx
PDF
Dive into Python Functions Fundamental Concepts.pdf
PPTX
Co&amp;al lecture-07
PPTX
Numerical data.
PPTX
ExamRevision_FinalSession_C++ notes.pptx
PDF
Aaa ped-23-Artificial Neural Network: Keras and Tensorfow
PPTX
Programming in C sesion 2
PPTX
Python For Data Science.pptx
PPTX
PPTX
C++ tutorial assignment - 23MTS5730.pptx
PPT
chapter-7-runtime-environments.ppt
PPTX
component of c language.pptx
1-Intoduction ------------- Array in C++
Function Overloading Call by value and call by reference
C Programming - Refresher - Part II
Unit 3(Arrays).pptx arrays topics in the c lang
Lecture 8
data structures using C 2 sem BCA univeristy of mysore
Pointers in c++
c++ arrays and pointers grade 9 STEP curriculum.pptx
Dive into Python Functions Fundamental Concepts.pdf
Co&amp;al lecture-07
Numerical data.
ExamRevision_FinalSession_C++ notes.pptx
Aaa ped-23-Artificial Neural Network: Keras and Tensorfow
Programming in C sesion 2
Python For Data Science.pptx
C++ tutorial assignment - 23MTS5730.pptx
chapter-7-runtime-environments.ppt
component of c language.pptx
Ad

More from malavshah9013 (20)

PDF
gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdf
PDF
Fill in parameters Public New Hash table (int initial Capacity, floa.pdf
PDF
For Phantom Limb Syndrome, please describe the symptoms and the part .pdf
PDF
Explain why the organisms that were studied by Sergei Winogradsky co.pdf
PDF
Electron transport powers the first steps of photosynthesis. The fo.pdf
PDF
Describe 5 key traits the lung cancer cells within the primary tumor.pdf
PDF
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
PDF
English Composition II - mutiple questions on researchQuestion 1 o.pdf
PDF
Customers arrive at a bank tellers booth at a rate of 2 per minute.pdf
PDF
Create a JAVA program that performs file IO and database interaction.pdf
PDF
Wolves were hunted and poisoned to extinction in Sweden and Norway b.pdf
PDF
Describe the differences between OpenPGP, PGP and GPG.Solution.pdf
PDF
Who identified three key economic “advantages” that firms should hav.pdf
PDF
Which of these is the largesta. The surface zoneb. The mixed la.pdf
PDF
Which of the following concepts is exemplified by the story of Parus .pdf
PDF
You will be implementing the following functions. You may modify the.pdf
PDF
When Elvis swims with the current, he swims 18km in 2 hours. Against.pdf
PDF
What tarsal is lateral to the medial cuneiform What tarsal is .pdf
PDF
What is the definition of memory access timeA. The difference bet.pdf
PDF
What are the main challenges to be dealt within a distributed operat.pdf
gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdf
Fill in parameters Public New Hash table (int initial Capacity, floa.pdf
For Phantom Limb Syndrome, please describe the symptoms and the part .pdf
Explain why the organisms that were studied by Sergei Winogradsky co.pdf
Electron transport powers the first steps of photosynthesis. The fo.pdf
Describe 5 key traits the lung cancer cells within the primary tumor.pdf
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
English Composition II - mutiple questions on researchQuestion 1 o.pdf
Customers arrive at a bank tellers booth at a rate of 2 per minute.pdf
Create a JAVA program that performs file IO and database interaction.pdf
Wolves were hunted and poisoned to extinction in Sweden and Norway b.pdf
Describe the differences between OpenPGP, PGP and GPG.Solution.pdf
Who identified three key economic “advantages” that firms should hav.pdf
Which of these is the largesta. The surface zoneb. The mixed la.pdf
Which of the following concepts is exemplified by the story of Parus .pdf
You will be implementing the following functions. You may modify the.pdf
When Elvis swims with the current, he swims 18km in 2 hours. Against.pdf
What tarsal is lateral to the medial cuneiform What tarsal is .pdf
What is the definition of memory access timeA. The difference bet.pdf
What are the main challenges to be dealt within a distributed operat.pdf
Ad

Recently uploaded (20)

PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Lesson notes of climatology university.
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Cell Structure & Organelles in detailed.
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Institutional Correction lecture only . . .
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Lesson notes of climatology university.
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Microbial diseases, their pathogenesis and prophylaxis
Cell Structure & Organelles in detailed.
Anesthesia in Laparoscopic Surgery in India
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Chinmaya Tiranga quiz Grand Finale.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Complications of Minimal Access Surgery at WLH
Final Presentation General Medicine 03-08-2024.pptx
Institutional Correction lecture only . . .
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Pharmacology of Heart Failure /Pharmacotherapy of CHF

Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdf

  • 1. Declaring a Pointer To define a pointer, use an asterisk, (*), in the declaration to specify the variable will be a pointer to the specified data type. Recall that the name of an array holds the memory address of the first element of the array. The second statement then would store the memory address of the first value in the variable valuePtr. The name of a pointer is an identifier and must follow the rules for defining an identifier. Some programmers place the letters ptr, a common abbreviation for pointer, at the end of the variable name, others prefix a pointer with p_ or ptr_, and there are those who do nothing to distinguish a pointer by its name. The naming of a pointer variable is a matter of programming style. Once a pointer has been declared and initialized, it can be used to access the data to which it points. In order to access this value, the dereference operator, *, must be used to prefix the name of the pointer. From the code above, valuePtr holds the address of the first element of the values array; therefore, *valuePtr will access the value 325. Add the following to main and execute the program. The output generated should look something like the following. Where 0xbfad43e8 is a memory address displayed in hexadecimal. Obtaining the Memory Address of a Variable The address operator, &, is used to determine the memory address of a variable that is not an array. Add code necessary to use fixed and setprecision, then add the following to main and run the program to confirm the use of the address operator. Using a Pointer to Alter Data Just as the dereference operator is used to retrieve data, so too is it used to store data. Add the following to function main and run the program. The pointer, ratePtr, is used to change the data stored in payRate. The output of payRate confirms the change. Using a Pointer in an Expression As previously shown, the value pointed to by a pointer variable can be retrieved by dereferencing the pointer. In the above code, the retrieved value was simply displayed to the screen; however, it can also be used in an expression. Add the following to main and execute the program. Pointer Arithmetic It is possible to add to or subtract from a memory address stored in a pointer. These actions can be accomplished using the addition operator,+, subtraction operator, - and the increment and decrement operators, ++ and --. This is helpful when accessing arrays via pointers. The increment operator has been used to add the value 1 to a variable. When used with a pointer, the increment operator adds the size of the data referenced to the memory address stored in the
  • 2. pointer, effectively moving the pointer to the next data value. Building on the code from above, add the following to main and execute the program. We initialized valuePtr to the memory address of the first element of the array values. Incrementing valuePtr instructs the computer to add four bytes, the size of an integer, to the memory addressed stored in valuePtr. After the increment, valuePtr now points to the second element of the array. The addition operator, +, works in a similar fashion. Add the following to function main and execute the program. Note that the value stored in valuePtr is not modified by this code. valuePtr currently points to the second element in the array. The program interprets the instruction to add two, *(valuePtr + 2), as add two times the size of an integer to the contents of valuePtr and access that address; this would be the fourth element of the array. The next line of code allows the confirmation of the interpretation of the addition by displaying the value in the fourth element of the array. The last line of code is included to demonstrate the need for the parenthesis when using the dereference operator when using the addition operator to alter the memory address. Add code to test the necessity of using parenthesis with the increment operator. The subtraction and decrement operators perform in a similar manner. Pointers as Parameters As with any other variable, pointers may be passed to functions as parameters. In a previous lab, a memory addressed was passed to a function using a reference parameter. The idea here is the same, only the syntax has changed. A pointer parameter is specified using the same syntax as a pointer declaration. Within the function itself, the pointer is used as before; the name of the pointer holds the memory address and the data can be accessed by dereferencing the pointer. Add the following function to the program. The function call must match the function definition. The function definition has specified that the function expects a memory address; the function call must therefore send the function a memory address. Add the following to main and execute the program. Because the pointer is a memory address, changes to the data value within the function will be seen outside the function. When passing an array via a pointer, the data values can be accessed using array notation or pointer notation. Add the following to the program. Add the following to function main and execute the program. The name of an array holds the memory address of the first element of the array; therefore, the name of an array is essentially a pointer to the first element of the array. Recall that the index specified within the [] operator, in array notation, instructs the computer to move that many
  • 3. elements from the first element. The computer calculates the distance to move using the same method as pointer arithmetic; the index value is multiplied by the size of the data type to determine the distance to move from the memory address of the first element. Just to help you practice with pointer math, replace the previous array notation version of displayArray with the following pointer notation version and execute the program. One final array notation option exists for the displayArray function. While an array name's value cannot change, a pointer's value can change. When an array is declared, the name of the array holds the memory address of the first element. If this value could be changed, there would be no way to retrieve the original memory address and data would be lost. The name of an array is a constant pointer. The pointer itself cannot change. When passing an array to a function, the memory address is passed to a pointer; this pointer is not a constant pointer and can be changed. There is no danger in changing the pointer's value (or memory address) in the function as the name of the array, in the calling function, still holds the original memory address. Replace the previous pointer notation version of displayArray with the following pointer notation version and execute the program. Dynamic Memory Allocation A variable declaration reserves memory for a variable. The amount of memory to be reserved must be known by the programmer. However, there are instances when the programmer may not know the exact amount of memory that will be needed by those that will use the program. As an example, recall from a previous lab the declaration of an array to store student scores. As the number of students was unknown, the array was declared large enough to store scores for double the largest expected class size. This approach works well until the assumption of the expected class size is no longer valid. A better approach might be to reserve the amount of memory needed at the time of the program's execution. In this example, that would require the program to first determine the number of students in the class, and then reserve that amount of memory. However, when declaring an array, the size must be an integer constant or literal; it cannot be a variable. The new Operator The new operator allows the program to dynamically, at run-time, reserve memory. The new operator has one operand on its right which specifies the amount, or size, of memory to allocate. The new operator returns the memory address of the allocated memory. Where size_to_allocate is typically a data type and pointerName has been declared a pointer of that type. Once allocated, the memory can be accessed via the pointer as discussed previously. It is important to note that memory allocated in this way is not initialized just as local variables are not. Be sure to initialize the memory before accessing it in an expression.
  • 4. The delete Operator Once memory has been allocated using new, the memory is accessible until it is released using the delete operator. The delete operator releases any memory obtained by new so that it can be used for other purposes either later in the program or by another process running concurrently on the computer. Add the following to function main and execute the program. delete must never be used to release any memory not obtained via new. The address nullptr is reserved so that any attempt to dereference a pointer to that address will fail. You should always set an owning pointer to nullptr after freeing the memory that it was managing, since the address of that (now deallocated) memory is still stored in the pointer; leaving it intact opens you to the possibility of accidentally making use of a storage location that no longer belongs to your program. new[] and delete[] Use the [] operator in conjunction with new to dynamically allocate an array. Where arrayName has been declared a pointer to the specified data type. This instruction will allocate size_of_array many elements of data_type. As with any array, the elements will occupy consecutive memory addresses. As with any locally declared variable, the memory is not initialized. Use the [] operator in conjunction with delete to release any memory allocated with the new[] operator. Add the following to the program. Add the following to function main and execute the program. This code will reserve enough consecutive space in memory to store ten integers and the address of the first element will be stored in the pointer variable moreValues. While this code will dynamically allocate memory for the array, the literal 10 in the code still forces the programmer to determine the amount of memory needed prior to execution of the program. With new the programmer is no longer constrained to use a constant or literal to specify the size of the array. Replace the previous code in main with the following and execute the program. With this code, the programmer is no longer forced to decided memory usage prior to the program's execution. Here, the user specifies the number of elements that will be needed; that amount of memory and only that amount of memory is reserved. Memory allocated using new remains available until it is released. delete need not be used within the function using new. To demonstrate, modify the getData function as follows. Then modify main as follows and execute the program.Code Illustration
  • 5. Solution solution #include #include using namespace std; int main() { int values[5] = {325, 879, 120, 459, 735}; int *valuePtr = values; cout<<"the expected output"< #include #include using namespace std; int main() { double payRate = 7.25; double *ratePtr = &payRate; cout << fixed << setprecision(2); cout << "address of payRate: " << ratePtr << endl; cout << "data store in payRate: " << *ratePtr << endl << endl; } output address of payRate: 0x22fe30 data store in payRate: 7.25 //use pointer to alter the data #include #include #include using namespace std; int main()
  • 6. { double payRate = 7.25; double *ratePtr = &payRate; cout << fixed << setprecision(2); cout << "address of payRate: " << ratePtr << endl; cout << "data store in payRate: " << *ratePtr << endl << endl; *ratePtr = 10.50; cout << "altered value of payRate: " << payRate << endl << endl; } output address of payRate: 0x22fe30 data store in payRate: 7.25 altered value of payRate: 10.50 //array values #include #include #include using namespace std; void displayArray(int *array, int size) { cout << "Array values: "; for (int i=0; i < size; i++) cout << array[i] << endl; cout << endl; } int main() { int values[]={1,2,3,4,5} ; displayArray(values,5); } output array values 1 2
  • 7. 3 4 5 //array values #include #include #include using namespace std; void displayArray(int *array, int size) { cout << "Array values: "; for (int i=0; i < size; i++) cout << *(array + i) << endl; cout << endl; } int main() { int values[]={1,2,3,4,5} ; displayArray(values,5); } output Array values: 1 2 3 4 5 //allocate the size dynamically #include #include #include using namespace std; void displayArray(int *array, int size) { cout << "Array values: "; for (int i=0; i < size; i++,array++) // "moves" the pointer
  • 8. cout << *array << endl; cout << endl; } int main() { //int values[]={1,2,3,4,5} ; int* values = NULL; // Pointer to int, initialize to nothing. int n; cout<<"enter the size needed for array"<> n; // Read in the size values = new int[n]; // Allocate n ints and save ptr in a. for (int i=0; i int main() { double *dv = new double; *dv = 88.25; cout << "address of dv: " << dv << endl; cout << "value of dv: " << *dv << endl << endl; delete dv; dv = NULL; // NULL the pointer so that it cannot accidentally be dereferenced again. } output address of dv: 0x537410 value of dv: 88.25 0 //program #include #include #include using namespace std; void displayArray(int *array, int size) { cout << "Array values: "; for (int i=0; i < size; i++,array++) // "moves" the pointer cout << *array << endl; cout << endl; }
  • 9. void getData (int *array, int size) { for (int i=0; i> array[i]; } } int main() { int *moreValues = new int[10]; getData(moreValues,10); displayArray(moreValues,10); delete [] moreValues; } output Enter value 2: 2 Enter value 3: 3 Enter value 4: 4 Enter value 5: 5 Enter value 6: 6 Enter value 7: 7 Enter value 8: 8 Enter value 9: 9 Enter value 10: 10 Array values: 0 2 3 4 5 6 7 8 9 10
  • 10. //program #include #include #include using namespace std; void displayArray(int *array, int size) { cout << "Array values: "; for (int i=0; i < size; i++,array++) // "moves" the pointer cout << *array << endl; cout << endl; } void getData (int *array, int size) { for (int i=0; i> array[i]; } } int main() { int numberOfMoreValues; cout << "How many more values would you like to enter? "; cin >> numberOfMoreValues; int *moreValues = new int[numberOfMoreValues]; getData(moreValues,numberOfMoreValues); displayArray(moreValues,numberOfMoreValues); delete [] moreValues; moreValues =NULL; // NULL the pointer for safety. } output How many more values would you like to enter? 10 Enter value 1: 1 Enter value 2: 2 Enter value 3: 3 Enter value 4: 4
  • 11. Enter value 5: 5 Enter value 6: 6 Enter value 7: 7 Enter value 8: 8 Enter value 9: 9 Enter value 10: 10 Array values: 1 2 3 4 5 6 7 8 9 10 //program #include #include #include using namespace std; void displayArray(int *array, int size) { cout << "Array values: "; for (int i=0; i < size; i++,array++) // "moves" the pointer cout << *array << endl; cout << endl; } int *getData (int &numberOfMoreValues) { cout << "How many more values would you like to enter? "; cin >> numberOfMoreValues; int *dynamicArray = new int[numberOfMoreValues]; for (int i=0; i> dynamicArray[i]; }
  • 12. return dynamicArray; } int main() { int numberOfMoreValues; int *moreValues = getData(numberOfMoreValues); displayArray(moreValues,numberOfMoreValues); delete [] moreValues; moreValues = NULL; // NULL the pointer for safety. } output How many more values would you like to enter? 5 Enter value 1: 20 Enter value 2: 30 Enter value 3: 40 Enter value 4: 50 Enter value 5: 60 Array values: 20 30 40 50 60