C:在动态结构中使用指针时"lvalue required as left operand of assignment"



程序必须扫描零之前的数字序列,然后再扫描一个数字并删除所有等于最后一个的数字。

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int elem;
    struct node *next;
};
void print(struct node *list)
{
        while (list != NULL)
        {
                if (list -> elem != 0)
                        printf("%d ", list -> elem);
                list = list -> next;
        }
        printf("n");
}
void push_back(struct node *list, int value)
{
        struct node *ptr;
        ptr = (struct node*)malloc(sizeof(struct node));
        ptr -> elem = value;
        ptr -> next = NULL;
        while (list -> next != NULL)
                list = list -> next;
        list -> next = ptr;
}
int pop_front(struct node *list)
{
        int value;
        struct node *ptr;
        ptr = list -> next;
        value = ptr -> elem;
        list -> next = ptr -> next;
        free(ptr);
        return value;
}
int main()
{
        struct node head = {0, NULL};
        int x;
        scanf("%d", &x);
        while (x != 0)
        {
                push_back(&head, x);
                scanf("%d", &x);
        }
        print(&head);
        scanf("%d", &x);
        while (head.next != NULL)
        {
                if (head.elem == x)
                        pop_front(&head);
                &head = head.next;
        }
        printf("n");
        print(&head);
        return 0;
}

线路出现故障

&head = head.next;
5.c:65:10: error: lvalue required as left operand of assignment

但是怎么了?例如,我不是在函数打印中也这样做过吗?

在打印功能中,要在列表中移动,请执行以下操作:

list = list -> next;

在主功能中,您可以执行:

&head = head.next;

看到区别了吗?

引用C11标准,第§6.5.16章

赋值运算符应具有可修改的左值作为其左操作数

在代码中,headstruct node类型的变量,该变量的地址不是可修改的左值。

要给某个变量赋值,需要有一个可修改的左值,而&head不是可修改的左值。

您可能需要一个指针,可以为其分配另一个地址(记住,而不是指针的地址)。

必须使用head作为指针。如果您将其声明为静态变量,则无法更改其地址。因此代码&head=head.next是无效的

压平运算符&的结果不是左值。它是一个临时值,等于其操作数的地址。

考虑到你对清单的设计是错误的。head应该像列表中的所有其他节点一样动态分配,或者您应该定义一个类似list的结构,该结构将包含指向head节点的指针。

例如,像这个一样声明头部

struct node head = NULL;

或者再定义一个结构

struct list
{
    node *head;
};
//...
int main( void )
{
    struct list lst;
    //,,,

但在这两种情况下,您都应该重写其他函数。

&headhead的内存地址。不能更改变量的地址。

相关内容

最新更新