So right now i am tasked to print out some ASCII art. I am told to use a Char ** private variable. So I made a 2D dynamic array of pointers with it, with all of the values being of any 'char' i choose. I was also told to make a to_string method which should store the contents of the array in a string and return the string. When I return the string, it prints out fine but at the end of each row, an extra garbage character is printed out. SO my question is, if my code is wrong or i'm not understanding something.
//note that C is already a private variable in the class
Canvas::Canvas(int width, int height)
{
this->_width=width;
this->_height=height;
this->C=newchar* [height];
for(int i=0;i<height;i++)
{
C[i]=newchar[width];
}
for(int i=0;i<height;i++)
{
for(int j=0;j<width;j++)
{
C[i][j]='#';
}
}
}
string Canvas::to_string()
{
int height=this->_height;
std::string copy;
for(int i =0;i<height;i++)
{
std::string roasted;
roasted+=C[i];
roasted+="\n";
copy+=roasted;
}
return copy;
}
//and if i try to print out a 4x6 array. Any other array size will also print fine but with the extra garbage at the end of each row :
####└
####└
####└
####└
####└
####└
//why is there an extra character at the end of each row ?
> why is there an extra character at the end of each row ?
Line 32: roasted+=C[i]; engenders undefined behaviour.
The rows do not contain null-terminated C-style strings (there is no null character at the end of C[i]).
std::string roasted(C, C + _width); // NOTE: constructor (7) is used
//roasted+=C[i]; // NOTE: This requires a terminating 0
roasted+="\n";
copy+=roasted;
when i try to add std::string roasted(C, C + _width); , it gives me a bunch of errors saying i need import. Im only allowed to use the <string> import.