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
}
};
c-style arrays are not copyable like that, if you want to copy one, you have to copy the content instead:
However, low-level features like c-style arrays, are best avoided.
If what you really wanted was a variable length string, use
std::string
instead, it supports copying via assignment operator.If you really wanted a fixed length array, use
std::array<T,N>
instead, it also supports copying via assignment operator.Also note, a recommendation is that parameter names and member variable names are distinct, except for constructors where you use the member initialization syntax:
Also note, if you planning on having setters and getters for all member variables, may I recommend public data instead, at least if the class does not have an class-invariant.
Let's take this example.
In case of C++, the array name
arr1
does not get a separate memory location. It's true thatarr1
sort of holds the memory location ofarr1[0]
but that is more of an oversimplification. The way arrays are referenced in C++ is via the symbol table. When an array is created, what actually happens is corresponding toarr1
an entry is created in the symbol table at compile time and this entry contains the information about the data-typearr1
refers to (which here is an integer-type array) and the address ofarr1[0]
. Now, here lies the interesting thing. Once an entry is created in the symbol table, C++ does not allow for it be changed.If you do
arr1=arr2
, what you are essentially trying to do is reassignarr1
to the entry corresponding toarr2
in the symbol table. Butarr1
has already been assigned some value in the symbol table. So C++ will give you an error.Because when you have a function call like this
UCSDStudent( char name[] )
only the adress of the arrayname
is copied instead of the whole array. It is a C\C++ feature.Furthermore the
name
defined aschar 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 tothis->name
too. You may read more aboutstrcpy
hereIf you still want to assign array to array, use a loop.
for eg: class UCSDStudent {
Because you assingned name as an array so you can not copy just like that and there is 21 count which name has. You must use "=" to copy an with loops and you have to identify array's count.