In: Computer Science
Leave comments on code describing what does what
Objectives:
1. To introduce pointer variables and their relationship with arrays
2. To introduce the dereferencing operator
3. To introduce the concept of dynamic memory allocation
A distinction must always be made between a memory location’s address and the data stored at that location. In this lab, we will look at addresses of variables and at special variables, called pointers, which hold these addresses.
The address of a variable is given by preceding the variable name with the C++ address operator (&). The & operator in front of the variable sum indicates that the address itself, and not the data stored in that location.
cout << ∑ // This outputs the address of the variable sum
To define a variable to be a pointer, we precede it with an asterisk (*). The asterisk in front of the variable indicates that ptr holds the address of a memory location.
int *ptr;
The int indicates that the memory location that ptr points to holds integer values. ptr is NOT an integer data type, but rather a pointer that holds the address of a location where an integer value is stored.
Explain the difference between the following two statements:
int sum; // ____________________________
int *sumPtr; // ___________________________
Using the symbols * and &:
The & symbol is basically used on two occasions.
reference variable : The memory address of the parameter is sent to the function instead of the value at that address.
address of a variable
void swap (int &first, int &second) // The & indicates that the parameters
{ // first and second are being passed by reference.
int temp;
temp = first; // Since first is a reference variable,
// the compiler retrieves the value
// stored there and places it in temp.
first = second // New values are written directly into
second = temp; // the memory locations of first and second.
}
2) The * symbol is used on
define pointer variables:
the contents of the memory location
int *ptr;
Experiment 1
Step 1:
Complete this program by filling in the code (places in bold). Note: use only pointer variables when instructed to by the comments in bold. This program is to test your knowledge of pointer variables and the & and * symbols.
Step 2:
Run the program with the following data: 10 15. Record the output here .
// This program demonstrates the use of pointer variables
// It finds the area of a rectangle given length and width
// It prints the length and width in ascending order
#include <iostream>
using namespace std;
int main()
{
int length; // holds length
int width; // holds width
int area; // holds area
int *lengthPtr; // int pointer which will be set to point to length
int *widthPtr; // int pointer which will be set to point to width
cout << "Please input the length of the rectangle" << endl;
cin >> length;
cout << "Please input the width of the rectangle" << endl;
cin >> width;
// Fill in code to make lengthPtr point to length (hold its address)
// Fill in code to make widthPtr point to width (hold its address)
area = // Fill in code to find the area by using only the pointer variables
cout << "The area is " << area << endl;
if (// Fill in the condition length > width by using only the pointer variables)
cout << "The length is greater than the width" << endl;
else if (// Fill in the condition of width > length by using only the pointer
// variables)
cout << "The width is greater than the length" << endl;
else
cout << "The width and length are the same" << endl;
return 0;
}
Experiment 2: Dynamic Memory
Step 1:
Complete the program by filling in the code. (Areas in bold) This problem requires that you study very carefully. The code has already written to prepare you to complete the program.
Step 2:
In inputting and outputting the name, you were asked NOT to use a bracketed subscript. Why is a bracketed subscript unnecessary? Would using name [pos] work for inputting the name? Why or why not? Would using name [pos] work for outputting the name? Why or why not?
Try them both and see.
// This program demonstrates the use of dynamic variables
#include <iostream>
using namespace std;
const int MAXNAME = 10;
int main()
{
int pos;
char * name;
int * one;
int * two;
int * three;
int result;
// Fill in code to allocate the integer variable one here
// Fill in code to allocate the integer variable two here
// Fill in code to allocate the integer variable three here
// Fill in code to allocate the character array pointed to by name
cout << "Enter your last name with exactly 10 characters." << endl;
cout << "If your name has < 10 characters, repeat last letter. " << endl
<< "Blanks at the end do not count." << endl;
for (pos = 0; pos < MAXNAME; pos++)
cin >> // Fill in code to read a character into the name array // WITHOUT USING a bracketed subscript
cout << "Hi ";
for (pos = 0; pos < MAXNAME; pos++)
cout << // Fill in code to a print a character from the name array // WITHOUT USING a bracketed subscript
cout << endl << "Enter three integer numbers separated by blanks" << endl;
// Fill in code to input three numbers and store them in the
// dynamic variables pointed to by pointers one, two, and three.
// You are working only with pointer variables
//echo print
cout << "The three numbers are " << endl;
// Fill in code to output those numbers
result = // Fill in code to calculate the sum of the three numbers
cout << "The sum of the three values is " << result << endl;
// Fill in code to deallocate one, two, three and name
return 0;
}
Sample Run:
Enter your last name with exactly 10 characters.
If your name < 10 characters, repeat last letter. Blanks do not count.
DeFinooooo
Hi DeFinooooo
Enter three integer numbers separated by blanks
5 6 7
The three numbers are 5 6 7
The sum of the three values is 18
Experiment 3: Dynamic Arrays
Question: Fill in the code as indicated by the comments in bold.
// This program demonstrates the use of dynamic arrays
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float *monthSales; // a pointer used to point to an array
// holding monthly sales
float total = 0; // total of all sales
float average; // average of monthly sales
int numOfSales; // number of sales to be processed
int count; // loop counter
cout << fixed << showpoint << setprecision(2);
cout << "How many monthly sales will be processed? ";
cin >> numOfSales;
// Fill in the code to allocate memory for the array pointed to by
// monthSales.
if ( // Fill in the condition to determine if memory has been
// allocated (or eliminate this if construct if your instructor
// tells you it is not needed for your compiler)
)
{
cout << "Error allocating memory!\n";
return 1;
}
cout << "Enter the sales below\n";
for (count = 0; count < numOfSales; count++)
{
cout << "Sales for Month number "
<< // Fill in code to show the number of the month
<< ":";
// Fill in code to bring sales into an element of the array
}
for (count = 0; count < numOfSales; count++)
{
total = total + monthSales[count];
}
average = // Fill in code to find the average
cout << "Average Monthly sale is $" << average << endl;
// Fill in the code to deallocate memory assigned to the array.
return 0;
}
Sample Run:
How many monthly sales will be processed 3
Enter the sales below
Sales for Month number 1: 401.25
Sales for Month number 2: 352.89
Sales for Month number 3: 375.05
Average Monthly sale is $376.40
Experiment 1: Experiment 1 is for how to use the pointer operator appropriately. As per the Question, the program to be filled with appropriate code using the pointer concept.
Pointer: pointer is a variable that holds the address of another variable. Pointers are used to access the variables dynamically. * and & operators are used to declaring a pointer variable.
if declare a variable preceding * then it will be called as a pointer variable. & is used to assign the variable address to the pointer variable.
Example
int a, *b; // a is regular integer variable whereas b is a pointer variable
a=10; //a is assigned with value 10
b=&a; //b is assigned with address of a
cout<<a; // it prints a i.e.,10
cout<<b; //it prints address of a for ex, 0011
cout<<*b //here *b is represented as "value at b". it results 10.
Explanation:
int sum; //it is normal integer variable
int *sumptr; //it is a pointer variable
Program step1:
#include <iostream>
using namespace std;
//main methods starts
int main()
{
int length; // holds length
int width; // holds width
int area; // holds area
int *lengthPtr; // int pointer which will be set to point to
length
int *widthPtr; // int pointer which will be set to point to
width
cout << "Please input the length of the
rectangle" << endl;
cin >> length;
cout << "Please input the width of the rectangle" <<
endl;
cin >> width;
// code to make lengthPtr point to length (hold its address)
lengthPtr=&length;
// code to make widthPtr point to width (hold its address)
widthPtr=&width;
// code to find the area by using only the pointer variables
area
=((*lengthPtr)*(*widthPtr)); //area
= length*width
cout << "The area is " << area << endl;
// the condition length > width by using only the pointer
variables
if (*lengthPtr > *widthPtr)cout << "The length is greater
than the width" << endl;
// Fill in the condition of width > length by using only the
pointer
else if (*widthPtr >*lengthPtr)
cout << "The width is greater than the length" <<
endl;
else
cout << "The width and length are the same" <<
endl;
return 0;
}
Step2: run the code using 10 and 15
Please input the length of the rectangle
10
Please input the width of the rectangle
10
The area is 150
the width is greater than length.
------------------------------------------------------
Experiment 2:
Explanation: Dynamic memory allocation is the process of allocating memory in runtime. this helps the programmer to allocate the memory at runtime without wasting the memory.
new and delete are the two keywords used to allocate the memory and deallocate it. By deallocating the allocated memory the program can use the deallocated memory again without creating unnecessary garbage in memory.
syntax:
int *n= new int[10]; // array declaration using dynamic memory
char *nm=new char[20]; //string declaration
here we need not use brackets to access the array values.that can be done in an easy way like.
n[0] represents n+i where i=1 automatically add 2 ytes to the pointer n.so it represents the next location
n[1] represents n+i here i will be 2
same applies to strings as well.
deallocating also very simple.
delete[] n; //deletes entire array once
delete[] nm; //deletes string array.
Step1:Program with filled code
#include <iostream>
using namespace std;
const int MAXNAME = 10;
int main ()
{
int pos;
char *name;
int *one;
int *two;
int *three;
int result;
// code to allocate the integer variable one here
one = new int;
// Fill in code to allocate the integer variable two here
two = new int;
// code to allocate the integer variable three here
three = new int;
// code to allocate the character array pointed to by name
name = new char[MAXNAME];
cout << "Enter your last name with exactly 10 characters."
<< endl;
cout << "If your name has < 10 characters, repeat last
letter. " << endl
<< "Blanks at the end do not count." << endl;
for (pos = 0; pos < MAXNAME; pos++)
// code to read a character into the name array // WITHOUT USING a
bracketed subscript
cin >> *(name + pos);
cout << "Hi ";
for (pos = 0; pos < MAXNAME; pos++)
// Fill in code to a print a character from the name array //
WITHOUT USING a bracketed subscript
cout << *(name + pos);
cout << endl << "Enter three integer numbers separated by blanks" << endl;
// Fill in code to input three numbers and store them in
the
std::cin >> *one >> *two >>
*three;
// dynamic variables pointed to by pointers one, two, and
three.
// You are working only with pointer variables
//echo print
cout << "The three numbers are " << endl;
// code to output those numbers
std::cout << *one << *two << *three;
result = *one + *two + *three; // code to calculate the
sum of the three numbers
cout << "The sum of the three values is " << result << endl;
return 0;
//code to deallocate one, two, three and name
delete (one);
delete (two);
delete (three);
}
step2:
Enter your last name with exactly 10 characters.
If your name has < 10 characters, repeat last letter.
Blanks at the end do not count.
sasanknknk
Hi sasanknknk
Enter three integer numbers separated by blanks
6 7 8
The three numbers are
678
The sum of the three values is 21
Experiment 3:
step1:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float *monthSales; // a pointer used to point to an array
// holding monthly sales
float total = 0; // total of all sales
float average; // average of monthly sales
int numOfSales; // number of sales to be processed
int count; // loop counter
//cout << fixed << showpoint <<
setprecision(2);
cout << "How many monthly sales will be processed? ";
cin >> numOfSales;
// code to allocate memory for the array pointed to by
monthSales.
monthSales= new float(numOfSales);
if (!monthSales)
//the condition to determine if memory has been allocated
{
cout << "Error allocating memory!\n";
return 1;
}
cout << "Enter the sales below\n";
for (count = 0; count < numOfSales; count++)
{
cout << "Sales for Month number "
<< (count+1)// code to show the number of the month
<< ":";
// code to bring sales into an element of the
array
cin>>*(monthSales+count);
}
for (count = 0; count < numOfSales; count++)
{
total = total + monthSales[count];
}
average = total/numOfSales;// code to find the average
cout << "Average Monthly sale is $" << average << endl;
//the code to deallocate memory assigned to the array.
delete[] monthSales;
return 0;
}
step2:
How many monthly sales will be processed? 5
Enter the sales below
Sales for Month number 1:56
Sales for Month number 2:64
Sales for Month number 3:45
Sales for Month number 4:34
Sales for Month number 5:65
Average Monthly sale is $52.8