Implement a small program that defines a regular number type variable , and a po
ID: 3716397 • Letter: I
Question
Implement a small program that defines a regular number type variable, and a pointer variable to the same type of number. Create these variables before starting steps 1-11 below. Only one regular variable and one pointer variable should be created for this assignment.
Use these variables for the following tasks (be sure to label each of these tasks, using comments):
1) ask the user for a value and store it in the regular variable
2) make the pointer variable point to the regular variable location
3) use both the regular variable and pointer variable to print the VALUE stored and the ADDRESS the value is stored at (four things should be printed, some will be the same)
4) use the pointer variable to allocate memory for a single value
5) store a value into this newly allocated memory
6) print the same items as in step 3 (print the original value & address as well as the newly allocated value and address)
7) deallocate the memory allocated in step 5
8) ask the user for a small number and use the pointer variable to allocate memory for an array of that size of the appropriate number type
9) store random values in all elements of this newly allocated array (use array notation)
10) print all elements of the array (use array notation)
11) deallocate any allocated memory and end the program
The files must be named lab7.cpp. Put your name and the file name as the first two (commented) lines in the file.
Explanation / Answer
// lab7.cpp.
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
//regular number variable
int n;
cout<<"enter the number ";
//input by user
cin>>n;
//pointer variable
int *a;
//a will point to the address of n
a=&n ;
//printing value of n and address of n in second time
cout<<n<<" "<<&n <<endl;
//printing value of the address pointed by a and address where a is pointing
cout<<*a<<" "<<a<<endl;
//allocating memory for single variable
int *p=new int;
// assinging value to the newly allocated value
*p=50000;
// printig the orogonal value and the address
cout<<*a<<" "<<a <<endl;
//printing newly allocated value and address
cout<<*p<<" "<<p<<endl;
delete(p);
// variable for size of an array
int size;
cout<<"Enter the size of the array ";
// enter the value of size
cin>>size;
// allocaring memory to the array of the entered size
int *arr=new int[size];
// assigning random values to all the array
for(int i=0;i<size;i++)
{
*(arr+i)=rand();
}
// printing the value of the array
for(int i=0;i<size;i++)
cout<<*(arr+i)<<" ";
// deallocating the values of the array
delete [] arr ;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.