简体   繁体   English

交换链表中的 arrays

[英]Swap arrays in linked list

So, I have to swap data of two nodes.所以,我必须交换两个节点的数据。 Here is the function i created:这是我创建的 function:

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错误如下: E0137 表达式必须是可修改的左值

Here is the struct st这是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;
};

You are trying to change where an array is when you do a->lname = b->lname;当您执行a->lname = b->lname;时,您正在尝试更改数组的位置. . That's not allowed.这是不允许的。 You would need to strcpy the string from one struct st to another.您需要将strcpy从一个struct st转换为另一个。 Also, struct st* temp;另外, 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.它没有指向任何已分配的 memory 因此程序在尝试使用它时具有未定义的行为。

Another option is to copy the whole struct st at once:另一种选择是一次复制整个struct st

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;
}

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 没有赋值运算符。 Arrays are non-modifiable lvalues. Arrays 是不可修改的左值。 And this error message而这个错误信息

E0137 expression must be a modifiable lvalue E0137 表达式必须是可修改的左值

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如果您需要为两个节点交换结构st的数据成员,那么 function 可以查看以下方式

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM