MECH 215 Assignment
Question #1
a) Develop a class (or structure) called “text” that contains a character pointer p. The pointer will point to a dynamically allocated character array (i.e. a string variable) that will be allocated and initialized in part b). The length of the array is given by the integer N.
Note a structure is the same as a class except the variables are public by default. Private variables are indicated with a “private:” keyword. Structures are not part of the course now, but you might see some old questions with structures. In that case use a class instead.
b) Develop a function called init_text(tx,n,str). This function will perform the following steps:
i) Initialize the member variable N in the text structure tx to n.
ii) Dynamically allocate (using new) a character array of length n storing the return value from new in the pointer variable p. Note the pointer variable p can be used like a character array (i.e. string) now due to the analogy between pointers and 1D arrays.
iii) Copy the string variable str into the dynamic character array p.
The function should return 1 if there is an error and 0 otherwise. Errors include returning NULL from the new operator and if the length of str (including the termination chatacter) is greater than n.
Hint: The C++ library functions strlen(…) and strcpy(…) can help you solve this problem.
c) Develop a function called delete_text(tx). This function will delete the dynamic array p and set it to NULL. Return 1 if there is an error (if p is already == NULL) and 0 otherwise.
Question #2
For the text structure of problem #1, add constructor and destructor member functions analogous to init_text(tx,n,str) and delete_text(tx). In that case there will be no tx argument (since N and p can be accessed in a member function). There will also be no return values, so just print an error message to the screen and return if there is an error. Finally, print out “\nconstructing” and “\ndestructing” at the beginning of the constructor and destructor, respectively. Example usage of the text structure is as follows:
text a(10,“apple”), b(20,“orange”);
cout “\n” < a.p;
which will output:
constructing
constructing
apple
destructing
destructing
Question #3
Develop an access member function for the text structure called get_text() that returns p by reference (i.e. put & in front of the function name). Example usage:
text a(10,“apple”), b(20,“orange”);
cout < “\n” < b.get_text();
which will output:
constructing
constructing
orange
destructing
destructing