Since we just looked at how to make dynamic copies of strings from the heap, her
ID: 3837097 • Letter: S
Question
Since we just looked at how to make dynamic copies of strings from the heap, here's a short exercise that lets you try it out for yourself. Write a main function that allows the user to enter five strings from the keyboard. As each string is entered, it will initially be saved in a local character buffer of substantial size. However, to be more efficient, you'll make a heap allocation to store only the space needed to contain a copy of the string in the buffer, just like we did in class. However, as each string is fetched from the user, the local character buffer will be passed as an argument to the MakeHeapStr function, which receives the cstring argument, allocates space from the heap to store a copy, copies the input cstring to the heap space, and returns a pointer to the heap string back to the caller What will the caller do with the return value? Well, if we were working with a single heap string we would probably catch the returned pointer in a local pointer to a char, However, since we're dealing with five heap strings, we'll use an array of pointers to chars! In other words, each individual array element is a single pointer to a char, which is suitable to store the value returned from the MakeHeapStr function. Once all five strings have been entered by the user at the keyboard, we'll display all of the strings to stdout before making sure to release them back to the heap.Explanation / Answer
#include <iostream>
#include <cstring>
using namespace std;
const int BUFLEN=256;
const int NUMSTRS = 5;
char* MakeHeapStr(char* str)
{
int len= strlen(str);
char* temp = new char[len];
strcpy(temp,str);
return temp;
}
int main()
{
char buf[BUFLEN];
char* charPtrs[NUMSTRS];
int index;
for(index=0;index<NUMSTRS;index++)
{
cout<<"Enter string #"<<index+1<<": ";
cin.getline(buf,sizeof(buf));
charPtrs[index]=MakeHeapStr(buf);
}
cout<<"Here are the strings you entered: ";
for(index=0;index<NUMSTRS;index++)
{
cout<<"#"<<index+1<<" "<<charPtrs[index]<<endl;
}
for(index=0;index<NUMSTRS;index++){
delete charPtrs[index];
}
}