So, I have to swap data of two nodes. Here is the function i created:
void swap(struct st* a, struct st* b)
{
struct st* temp;
temp->lname = a->lname; //lname is an array of chars
a->lname = b->lname;
b->lname = temp->lname;
temp->marks = a->marks; //marks is an array of doubles
a->marks = b->marks;
b->marks = temp->marks;
}
So i do not understand why an error occures. The error is following: E0137 expression must be a modifiable lvalue
Here is the struct st
#define N 20
#define M 5
struct st
{
char lname[N];
char fname[N];
int birth[3];
double marks[M];
double avarage_mark;
struct st* next;
};
CodePudding user response:
This declaration
struct st* temp;
declares an uninitialized pointer with an indeterminate value. So dereferencing the pointer as
temp->lname = a->lname;
invokes undefined behavior.
Secondly arrays do not have the assignment operator. Arrays are non-modifiable lvalues. And this error message
E0137 expression must be a modifiable lvalue
means that you are trying to assign one array to another.
If you need to swap data members of the structure st
for two nodes then the function can look the following way
void swap(struct st* a, struct st* b)
{
struct st temp = *a;
*a = *b;
*b = temp;
struct st *p = a->next;
a->next = b->next;
b->next = p;
}
CodePudding user response:
You are trying to change where an array is when you do a->lname = b->lname;
. That's not allowed. You would need to strcpy
the string from one struct st
to another. Also, struct st* temp;
is an uninitialized pointer. It doesn't point at any allocated memory so the program has undefined behavior trying to use it.
Another option is to copy the whole struct st
at once:
void swap(struct st* a, struct st* b)
{
struct st temp = *a; // initialize temp with *a
*a = *b;
*b = temp;
// swap next pointers back
b->next = a->next;
a->next = temp->next;
}