Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fix this lvalue warning?

Tags:

c++

arrays

My code is:

void main() {
 person student[10];
 
 student[0].names[0] = 'C';
 student[0].names[1] = 'a';
 student[0].names[2] = 'm';
 student[0].names[3] = 'i';
 student[0].ages = 16;
 student[0].sex[0] = 'F';
 student[0].sex[1] = 'e';
 student[0].sex[2] = 'm';
 student[0].sex[3] = 'a';
 student[0].sex[4] = 'l';
 student[0].sex[5] = 'e';
 student[0].month = 8;
 student[0].day = 2;
 student[0].year = 1993;
}

All of the "student" is underlined saying expression must be a modifiable lvalue. How can i fix this?

person

typedef struct person 
{ 
char names[20][10]; 
char sex[6][10]; 
int ages[10]; 
int month[10]; 
int day[10]; 
int year[10]; 
} person;
like image 329
Sarah Avatar asked Dec 07 '22 02:12

Sarah


1 Answers

Array usage

You say you have:

typedef struct person {
    char names[20][10];
    char sex[6][10];
    int ages[10];
    int month[10];
    int day[10];
    int year[10];
} person;

There's no need for the [10]'s. You already have that in the person student[10] declaration, which is the proper place for the [10]. Remove the extraneous arrays:

typedef struct person {
    char name[20];
    char sex[6];
    int age;
    int month;
    int day;
    int year;
} person;

String handling

Also your strings aren't null-terminated. In C strings need to have an extra '\0' character at the end to indicate where the end of the string is. Your name assignment, for example, should be:

student[0].name[0] = 'C';
student[0].name[1] = 'a';
student[0].name[2] = 'm';
student[0].name[3] = 'i';
student[0].name[4] = '\0';

Actually though, there's an easier way to assign to a string than to do it a character at a time. The strcpy function will copy an entire string in one go:

strcpy(student[0].name, "Cami");

Or, the easiest option of all is to use the string class available in C++. It makes string-handling a whole lot easier than the C way of manipulating character arrays. With the string class your code would look like this:

// Modified struct declaration.
typedef struct person {
    std::string name;
    std::string sex;
    int         age;
    // ...
} person;

// Modified assignment.
student[0].name = "Cami";
like image 94
John Kugelman Avatar answered Dec 11 '22 12:12

John Kugelman