Hi Folks,
Can anyone tell me why this console program errors out *after* it has correctly performed both of the show() functions? The program compiles without error or warning, which is why I don't understand what the problem is. I've isolated the problem enough to know it's somewhere in the set() function. This program was my solution to the following textbook exercise:
// Following is a program skeleton. Complete it by providing the
// described functions and prototypes. Note that there should be
// two show() functions, each using default arguments. Use const
// arguments when appropriate. Note that set() should use new to
// allocate sufficient space to hold the designated string. The
// techniques used here are similar to those used in designing
// and implementing classes. (You might have to alter the header
// file names and delete the using-directive, depending upon your
// compiler.)
And here is the skeleton, plus my code for the three functions (including prototypes):
Code:
#include <iostream>
using namespace std;
#include <cstring> // for strlen(), strcpy()
struct stringy
{
char * str; // points to a string
int ct; // length of string (not counting '\0')
};
/// These are my prototypes for the three functions, two of them overloaded
void set(stringy & x, char * y);
void show(const stringy & a, int b = 1);
void show(const char * c, int d = 1);
int main()
{
stringy beany;
char testing[] = "Reality isn't what it used to be.";
set(beany, testing); // first argument is a reference!
show(beany); // prints member string once
show(beany, 2); // prints member string twice
testing[0] = 'D';
testing[1] = 'u';
show(testing); // prints testing string once
show(testing, 3); // prints testing string thrice
show("Done!");
return 0;
}
void set(stringy & x, char * y) // 'x' is reference variable for stringy type "beany"
{
x.ct = strlen(y); // sets ct member of beany (length of testing string)
char * space = new char; // allocates space to hold copy of testing
space = x.str; // sets str member of beany to point to the new block
strcpy(space, y); // copies testing to new block
delete space; // releases memory allocated for space
}
void show(const stringy & a, int b)
{
for (int i = 0; i < b; i++)
cout << a.str << "\n";
}
void show(const char * c, int d)
{
for (int i = 0; i < d; i++)
cout << c << "\n";
}