Question: Please answer a-d, there was a previous post with additional questions. Thank you in advance. Consider the following program and provide code and explanations where
Please answer a-d, there was a previous post with additional questions. Thank you in advance.
Consider the following program and provide code and explanations where asked in the code comment after running the program in your system. Note that there are 4 places that need to be addressed.
#include
#include
using namespace std;
class Header{
private:
char used;
int payloadsize;
char* data;
public:
Header (){
used = 0, payloadsize = -1, data = NULL;
}
Header (int ps, char initvalue = 0){
used = 0;
payloadsize = ps;
data = new char [payloadsize];
memset (data, initvalue, payloadsize);
}
int getsummation (){
int sum = 0;
for (int i=0; i sum += data [i]; } return sum; } }; int main (){ Header h1; Header h2 (10); Header* h3 = new Header (20); cout << "Header type size " << sizeof (Header) << endl; // 1. explain cout << "Header oject size " << sizeof (h1) << endl; // 2. explain why cout << "Header object h2 size "<< sizeof (h2) << endl; // 3. explain why cout << "Header object pointer size " << sizeof (h3) << endl; // 4. why // a. now allocate memory big enough to hold 10 instances of Header // b. Put 10 instances of Header in the allocated memory block, one after another without overwriting // The instances should have payload size 10, 20,..., 100 respectively // and they should have initial values 1,2,...10 respectively // c. now call getsummation() on each instance using a loop, output should be: // 10, 40, 90, ...., 1000 respectively Header* ptr = h3 + 100; cout <<"Printing pointer h3: " << h3 << endl; cout <<"Printing pointer ptr: " << ptr << endl; // d. explain the output you see in the following cout << "Difference " << (ptr - h3) << " objects" << endl; cout << "Difference " << ((char*) ptr - (char *)h3) << " bytes" << endl; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
