Draw the memory map of the following code and write output of the program.

Question

Draw the memory map of the following code and write the output of the program.

#include <iostream>
using namespace std;
int* function(int* ptr1, int* ptr2)
{
*ptr *=2;
*ptr *=4;
int num = 100;
ptr1 = &num;
return ptr1;
}
void fillArray(int* arr, int size)
{
for(int i =0;i<size; i++)
arr[i]= i*3+2;
}
void printArray(int* arr, int size)
(
(int i=0; i<size; i++)
cout<<arr[i]<<" "'
}
int main()
{
int a = 10;
int b = 40;
int* aptr = &a;
int* bptr = &b;
int arr[10] = {};
int* arrptr = arr;
function(aptr.bptr);
fillArray(arrptr + 3, 5);
printArray(arr,10);
return 0;
}

Summary

We used a methods function naming as aptr, bptr which will give value in num with the address with the value 100. So next is the method named fillArray who’s work is to fill the array indexing from 3 to 7 with the given element such as 2,5,8,11,14. Method named printArray is used to print the array.

Explanation

Output
Here program have to called the function. Also the value returned by pointer will get printed which will return 100.

Draw the memory map

Memory Map

Here we have elements as int a=10; and int b=40;

Address: 1000

10

=a. Variable name for location 1000 is a.

Address:1004

40

=b. Variable name for location 1004 is b.

int * aptr=&a; → points to ‘a’ address

int * bptr=&b; → points to ‘b’ address

aptr ↓ 1000                        bptr ↓ 1004

10 40

 

int arr[10]={}

Memory allocation for memory of size 10

2001
2012
2015
2036
2065
2073
2018
2045
2027
2000

int b * arrptr=arr;

this arrptr points to the base address of ‘arr’

If the statement ‘function(aptr,bptr)’ is written as “cout<<*function(aptr,bptr)”, it displays 100.

function(aptr,bptr)

aptr ↓ 1000                                     *ptr1 *=2;

20

bptr ↓1004                                             *ptr2 * =4

int num=100;

num ↓ 1008

100

ptr1 = &num;

aptr ↓ 1008

100

Earlier aptr was pointing to address1000 having a value of 20, now it points to another address 1008, having a value 100.

return ptr1;

Finally function (aptr,bptr) will return the address 1008.


fillArray (arrptr +3,5);

arrptr points to 2000, but arrptr +3 is passed, so 2012 location is passed with size 5.

for(int i=0;i<size; i++)

arr[i]= i+3+2

(arrptr +3 to arrptr+3+5)

arr

arrptr

2000
arrptr+1 2027
arrptr+2 2045
arrptr+3 2 2018
arrptr+4 5 2073
arrptr+5 8 2065
arrptr+6 11 2036
arrptr+7 14 2015
arrptr+8 2012
arrptr+9 2001

here at the position of arrptr+3 the value of i=0 and i is incremented on every next stage.


printArray(arr,10)

All array elements are printed from index 0 to 9.

Output

0 0 0 2 5 8 11 14 0 0

 

Also read, define a class named StarterPokemon that contains.

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *