-
cannot convert
I'm trying to assign an array to an array however I'm having some problems,
here is my class;
Code:
class Transaction {
public:
Transaction::Transaction();
Transaction::Transaction(float InAmount, char InCode, char InNote[]);
int Transaction::SetAmount(float NewAmount);
float Transaction::GetAmount();
int Transaction::SetCode(char NewCode);
char Transaction::GetCode();
int Transaction::SetNote(char *NewNote);
int PrintNote();
private:
float Amount;
char Code;
char Note[20];
};
here is the overloaded constructor;
Code:
Transaction::Transaction(float InAmount, char InCode, char InNote[]) {
Amount = InAmount;
Code = InCode;
Note = InNote;
}
when I try to compile I get a "cannot convert from 'char []' to 'char [20]'" error.
If I declare note like this. "char *Note" it compiles fine but when I try to run the program it crashes....
can someone help??
-
> Note = InNote;
Use the strcpy() function to copy char arrays:
strcpy(Note, InNote);
To use strcpy, include <cstring>.
-
when you recompile it with char * Note it crashes because although that is the same type as an array, but you are only initializing what would be the first element of the array and when you try to overwrite the other elements it goes into unassinged memory. Initialize note as char [] instead of char[20] and give it its assignments later.
-
Of course, std::string from the <string> header is really a better choice than a statically sized array. All of the operations that are intuitive for arrays but fail work with std::strings.