Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I assign an array variable directly to another array variable with the '=' operator?

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 
    }

};
like image 269
Kacy Raye Avatar asked Mar 24 '23 12:03

Kacy Raye


2 Answers

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

like image 144
Alexandru Barbarosie Avatar answered Mar 26 '23 00:03

Alexandru Barbarosie


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];

  }
}
};  
like image 44
K L Avatar answered Mar 26 '23 02:03

K L