I am attempting a program using C++ that prints text to a terminal in different colors.
I have the following code which features the Color class nested into the letter_template typedef, further nested into an array of 100 letter_template’s:
class Color
{
private:
char contents[6];
public:
Color() {
short prepend = COLOR_PREPEND;
sprintf(contents, "%s[%dm", (char *)prepend, 0);
}
Color(int code) {
short prepend = COLOR_PREPEND;
sprintf(contents, "%s[%dm", (char *)prepend, code);
}
};
typedef struct {
Color *set;
char c;
Color *reset;
} letter_template;
letter_template essay[100];
int main() {
// Initialize array
for (int i = 0; i < sizeof(essay)/sizeof(essay[0]); i++) {
essay[i].set = new Color(); essay[i].reset = new Color();
}
return 0;
}
The segfault occurs on the first loop of the for loop, and using a debugger I noticed that the contents of every member of “essay” had null values (0x0) for both the “set” and “reset” attributes, so I guess it couldn’t initialize the Color objects. I cannot figure out why though.
At first what I was really trying to do was to have one long contiguous string of data in the order of color sequence > letter > color sequence > repeat, I know that what I have coded will not be exactly that, however I am at a loss for why it shouldn’t be working at least.
I am stumped because my Color class definition as you see it worked just fine before I put it into the class and typedef structure (as in, the sprintf statement as you see it worked fine when I just had it written in main). My “contents” attribute has 6 bytes which I know is enough space for what I am sprintf-ing there.