When i in class constructor "Cow" want to copy char string into variable char array name program was crashed. I dont understand whats problem. strcpy need char* dist and const char* Source. I given that, but its not working.What i do wrong?
Cow::~Cow() {
delete [] hobby;
}
Cow::Cow(const char* nm, const char* ho, double wt) {
if (strlen(nm) < 20)
strcpy(name, nm);
else strcpy(name, "FailLenghtName");
hobby = new char[strlen(ho)+1];
strcpy(hobby, ho);
weight = wt;
}
class Cow {
char name[20];
char* hobby;
double weight;
public:
Cow(const char* nm, const char* ho, double wt);
~Cow();
};
int main() {
Cow Liza("Liza","Meat",120);
}
I try use any func like sprintf, but result is same
Nothing is technically wrong with the code as presented (except the missing headers and using namespace std
, as Alan correctly observed).
The cast should not change anything; you are right that a string literal is an array of const char
and is "adjusted" when it is passed as a parameter to a pointer to const char
, which is what your constructor expects.
The constructor and destructor also seem to be correct, even though it would be better to not use literal numbers but a constant (or sizeof name
! But there is always a possibility that you'll change name
to also be a pointer, and then you are doomed) for the maximum string length, and — as always — much better to use the standard library facilities, here std::string
.
But those are issues for a code review and only indirectly concerned with correctness (because they reduce the chance to make a mistake and make it easier to spot them if they are made).
Oh, and Ahmed's comment about "the rule of 3/5" is actually very relevant here and may well be the cause for a crash as soon as your class is actually used: Copying or assigning cow
s will lead to a simple copy of the hobby pointer; both instances, the original and the copy, will attempt to delete the same pointer. Only the fist of the attempts will succeed, the second one will usually lead to a crash.