- (10%)
Determine whether the following code is correct or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
// strlen vs. sizeof
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
int main()
{
char s[20] = "This War Of Mine";
cout << strlen(s) << endl;
cout << sizeof(s) << endl;
return 0;
}
- (10%)Suppose
we compile and run the following code on a 64-bit host, where each
pointer (memory address) occupies 64 bits, and each character still
occupies 8 bits. Determine whether the following code is correct
or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
// Destructor
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
class CMessage
{
char* m_pMessage;
public:
CMessage(const char* text = "Default message")
{
m_pMessage = new char[strlen(text) + 1];
strcpy(m_pMessage, text);
}
~CMessage()
{
cout
<< "Destructor called for " << m_pMessage << ".\n";
delete [] m_pMessage;
}
};
int main()
{
CMessage game("Real War");
CMessage movie("Schindler's List");
cout << sizeof(game) << endl;
cout << sizeof(movie) << endl;
return 0;
}
- (10%)
Determine whether the following code is correct or not. If it is
correct, predict its output. If it is incorrect, point out the
mistake(s).
// Default Copy Constructor
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class CData
{
public:
int value;
int* pdata;
CData(int n=0)
{
value = n;
pdata = new(int);
*pdata = n;
// cout << "Constructor called with initial value " << n << endl;
}
void Print()
{
cout << value << '\t' << *pdata << endl;
}
};
int main()
{
CData a(5);
CData b = a;
b.Print();
a.value = *a.pdata = 20;
a.Print(); b.Print();
return 0;
}