In: Computer Science
C++ Memory Allocation:
1) Write a C++ program that allocates static, stack, & heap memory. Your program does not need to do anything else. Indicate via comments where memory for at least one variable in each memory area is allocated.
a) Write code that allocates static memory (only include one declaration):
b) Write code that allocates stack memory (only include one declaration):
c) Write code that allocates heap memory (only include one declaration):
2)
Edit the C++ program below to include a pointer and a reference to num. Print the number using both the pointer and the reference.
#include<iostream>
using namespace std;
int main()
{
int num = 10;
cout << "num = " << num << endl;
return 0;
}
a) Write code that declares a pointer to num:
b) Write code that declares a reference to num:
------------------------------------------------------------------------------------------------------------------------------------------------------------------
Please show the code and explain in comments! Show the output as well thank you
****This requires some effort so please drop a like if you are satisfied with the solution****
I have tried my best to make the explanation easy to understand through comments so please go through them for better understanding....
Q1. a,b,c
//static memory is allocated during compile time(static
allocation)
//Heap memory is allocated during run time throught (dynamic
allocation)
#include <iostream>
using namespace std;
//1. allocated on static memory
char * str1="Static memory";
//2. Staticlly allocated pointer
char * b;
int main(){
//3. this will be allocated on stack but will be destroyed when
main() returns
char * str2="Allocated on stack";
//4. this is same as 2 but static tells that it should not be
allocated on stack
static char * str3=str1;
//examples of static memory allocation
int a[10];
int x;
char c;
//examples of Heap memory allocation
int * array=(int*)malloc(10*sizeof(int));
//malloc make dynamic alloction which is on heap memory
}
Q2. a,b
#include <iostream>
using namespace std;
int main()
{
//declare an integer variable num=10
int num=10;
//declare a pointer variable p (a pointer variable is a variable
which is capable of storing address or reference of other
variable)
int *p;
//store the address or reference of num in p
p=#
//&x indicates the address of num which is stored in p i.e, p
is the address where value of num is
//if you want to access value at num address which is p you need to
specify *p here *p indicates the value of num
cout<<"num is "<<*p;
return 0;
}