I’m writing a simple program. There is only one class in it. There is a private member ‘char * number’ and two function (there will be more, but first these should work correctly 🙂 ).
The first one should copy the ‘source’ into ‘number’ variable (and I suppose somewhere here is the problem):
LongNumber::LongNumber(const char * source ){
int digits = strlen(source);
char* number = new char[digits+1];
strcpy( number, source );
// cout<<number<<endl; - if the line is uncommented,
// the output is correct and there isn't a problem
}
And a print function:
void LongNumber::print(){
cout<<number<<endl;
// when I try to print with the same line of code here..it crashes
}
Sure, I’m missing something…but what?
(As this is my first post…do you think the tags are corrected..how would you tagged the post?)
Thank you in advance 🙂
In the
LongNumberconstructor you declare a new local variable namednumberand initialize it with a newchararray:Instead you should leave out the
char*, so that it doesn’t look like a new variable declaration and uses the object member variable:With the current code, the member variable
numbernever gets initialized and using it later inprintleads to an error.