c++structlvalue

Expression must be Modifiable lvalue (char array)


I defined my struct as:

struct taxPayer{
  char name[25];
  long int socialSecNum;
  float taxRate;
  float income;
  float taxes; 
};

My main function contains:

taxPayer citizen1, citizen2;

citizen1.name = "Tim McGuiness";
citizen1.socialSecNum = 255871234;
citizen1.taxRate = 0.35;

citizen2.name = "John Kane";
citizen2.socialSecNum = 278990582;
citizen2.taxRate = 0.29;

The compiled gives me an error (C3863 array type char[25] is not assignable, expression must be a modifiable lvalue) on citizen1.name = "Tim McGuiness"; as well as on citzen2.name = "John Kane";

How do I remove this error and set citizen1.name to a name and citizen2.name to a different name?


Solution

  • You cannot assign to an array. What you can do is either use a std::string or use std::strcpy/std::strncpy, like

    std::strncpy(citizen1.name,"Tim McGuiness", sizeof(taxPayer::name));
    

    Since you use C++, I'd recommend using a std::string,

    struct taxPayer
    {
        std::string name;
        // the rest
    };
    

    then you can simply assign to it as you did in your code

    citizen1.name = "Tim McGuiness";