Why does the following assignment not work? I would like a low-level explanation if possible. Also, here's the compiler error I get: incompatible types in assignment of 'char*' to 'char [20]'
class UCSDStudent {
char name[20];
public:
UCSDStudent( char name[] ) {
//this-> name = name; does not work! Please explain why not
strcopy( this -> copy, copy ); //works
}
};
Because when you have a function call like this UCSDStudent( char name[] )
only the adress of the array name
is copied instead of the whole array. It is a C\C++ feature.
Furthermore the name
defined as char name [20]
is not a modifiable lvalue.
Regarding strcpy
: it will bring undefined behaivour as if your source array doesn't have a NULL character it will copy some trash to this->name
too. You may read more about strcpy
here
If you still want to assign array to array, use a loop.
for eg: class UCSDStudent {
char name[20];
public:
UCSDStudent( char name[] )
{
for(int i = 0; i<20; i++)
{
this-> name[i] = name[i];
}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With