Printing a char* in C++
c++, char, pointers, printing
Solution
In the `LongNumber` constructor you declare a new local variable named `number` and initialize it with a new `char` array:
char* number = new char[digits+1];
Instead you should leave out the `char*`, so that it doesn't look like a new variable declaration and uses the object member variable:
number = new char[digits+1];
With the current code, the member variable `number` never gets initialized and using it later in `print` leads to an error.
Problem
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 :)