0

I'm an extreme newbie, I'm just trying to learn.. this is my simple struct that I've created

struct Student{
char FirstName[20];
char LastName[20];
char StudentID[10];
char Password[20];}

Then I'm creating an array of pointers;

struct Student *StudentList[10];

I am then calling my "Register" function and passing the first element in the array as a parameter, for the reason of changing values to that specific struct element in the array, for example I want to change the student's details;

Register(&StudentList[0]);

Further on, my function;

void Register(struct Student *student);
void Register(struct Student *student) {student->FirstName = "John";}

This is a very simplified example and sorry for not being able to correctly paste in the code here.

But why am I getting an "expression must be a modifiable lvalue", when I try to assign a value.

Val
  • 57
  • 1
  • 6

4 Answers4

2

You can't assign array types like that in C, and "John" is an array of type char[5].

strcpy(student->FirstName, "John");

would do it or, better still, something of the form

strncpy(student->FirstName, "John", 20);

so you avoid overrunning the char buffer.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

The firstName field is an array, and arrays cannot be assigned to as a whole. That's what the error message is telling you.

Since you're copying a string into this array, you should use strcpy:

strcpy(student->FirstName, "John");
dbush
  • 205,898
  • 23
  • 218
  • 273
1

In C, you do not set strings using = (and you do not compare them using == either).

You must use the strcpy function:

strcpy( student->firstName, "John" );
abelenky
  • 63,815
  • 23
  • 109
  • 159
0

First thing you forget to put semicolon at the end of struct declaration struct Student { };

Secondly, you are passing &StudentList[0], instead just pass StudentList[0] and allocate memory dynamically for that first.

Finally, student->FirstName = "John"; because student->FirstName is one char buffer and "John" also one buffer so you can't do A = B where A and B both are char buffer, instead use strcpy(A,B);

Here is sample example

struct Student{
        char FirstName[20];
        char LastName[20];
        char StudentID[10];
        char Password[20];
}; /* you forget to put semicolon */
void Register(struct Student *student)  {
        strcpy(student->FirstName,"John"); /* use strcpy() */
        printf("%s\n",student->FirstName);
}
int main() {
        struct Student *StudentList[10];
        for(int index = 0;index < 10;index++) {
        StudentList[index] = malloc(sizeof(struct Student)); /* allocate memory for each Student */
        }
        Register(StudentList[0]);

        /* free the dynamically allocated memory */

        return 0;
}
Achal
  • 11,821
  • 2
  • 15
  • 37