Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression must be Modifiable lvalue (char array)

Tags:

c++

struct

lvalue

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?

like image 965
Zack Sloan Avatar asked May 04 '16 01:05

Zack Sloan


2 Answers

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";
like image 142
vsoftco Avatar answered Oct 17 '22 22:10

vsoftco


In c, an array is assignable only in the initialization period, citizen1.name is an array of char type. To solve your problem, you may use this:

strcpy(citizen1.name, "Tim McGuiness");

or:

memcpy(citizen1.name, "Tim McGuiness", strlen("Tim McGuiness"));
citizen1.name[strlen("Tim McGuiness") + 1] = '\0';
like image 2
weixt Avatar answered Oct 17 '22 22:10

weixt