In: Computer Science
Integer Pointers Program and Analysis
Demonstrate an understanding of basic C++ programming concepts by completing the following:
Hello,
Please go through code and output.
CODE:
#include <iostream>
using namespace std;
int main()
{
int v1 = 0, v2 = 0, v3 = 0; // initialize
variables
int *p1 = NULL, *p2 = NULL, *p3 = NULL; // initialize
pointers
cout << "Enter three integer values: " <<
endl; // ask user to enter number
cin >> v1 >> v2 >> v3;
/* give memory to pointers */
p1 = new int[1];
p2 = new int[1];
p3 = new int[1];
/* assign value to pointers */
p1[0] = v1;
p2[0] = v2;
p3[0] = v3;
/* print value */
cout << "v1 : " << v1 << endl;
cout << "v2 : " << v2 << endl;
cout << "v3 : " << v3 << endl;
cout << "p1 : " << p1[0] <<
endl;
cout << "p2 : " << p2[0] <<
endl;
cout << "p3 : " << p3[0] <<
endl;
/* delete allocated memory */
delete p1;
delete p2;
delete p3;
}
OUTPUT:
------------------------------------------------------------------------------------------------
In this program, we can see some of the problems can occur if we will not handle it.
1. p1, p2, p3 should allocate memory before assign value to it.
if we will not do it. segmentation fault will occur.
2. If we assign memory to pointer it should be free also.
If this not happen memory leak problem will occur.
3. after deleting the memory we need to assign null to the pointer.
If this will not happen sometime that pointer will still be pointing to that address and program will behave differently.