【问题标题】:lvalue required as left operand of an assignment?左值需要作为赋值的左操作数?
【发布时间】:2016-10-20 02:49:29
【问题描述】:

这是我的代码:

void pwd(Fs_sim *files) {
    Node *curr_node = files->curr;
    Node **space = NULL;
    int i = 0;

    while (curr_node->parent != NULL) {
        space = realloc(space, sizeof(Node *) * (i + 1));
        *space + i = curr_node;
        i++;
        curr_node = curr_node->parent;
    }
    if (i == 0)
        printf("/\n");
    else {
        while (i > 0) {
            printf("/%s", (*space + i--)->name);
        }

        printf("\n");
    }
    free(space);

}

'space' 是指向动态分配的数组的指针。随着每个节点的迭代,我想在动态分配的数组中存储一个指向该节点的指针,并计算有多少元素。我收到错误消息:

error: lvalue required as left operand of an assignment

在 '*space + i = curr_node;'行。

我看不出有什么问题。有人可以澄清一下吗?

更新:

我已经更改了代码并且现在可以编译,但是当我运行可执行文件时出现分段错误。这是我的代码:

void pwd(Fs_sim *files) {
    Node *curr_node = files->curr;
    Node **space = NULL;
    int i = 0;

    while (curr_node->parent != NULL) {
        space = realloc(space, sizeof(Node *) * (i + 1));
        *(space + i) = curr_node;
        i++;
        curr_node = curr_node->parent;
    }
    if (i == 0)
        printf("/\n");
    else {
        while (i >= 0) {
          printf("/%s", (*(space + (i-1)))->name);
          i--;
        }

        printf("\n");
    }
    free(space);

}

仍然找不到问题所在。

提前谢谢。这里是 C 的大菜鸟。

【问题讨论】:

  • 我想你的意思是*(space + i) = curr_node;
  • @VaughnCato: *(space + i) 最好写成space[i]

标签: c arrays pointers dynamic-memory-allocation


【解决方案1】:

我认为错误就在这里:

while (i >= 0) {
    printf("/%s", (*(space + (i-1)))->name);
    i--;
}

i 为 0 并且您尝试执行 (*(space + (i-1)))->name); 时会发生什么?

你会得到space + -1

【讨论】:

  • 谢谢你,一个愚蠢的错误。我太专注于内存分配而忘记检查这样的事情。
【解决方案2】:

更新前答案:

你好像把它翻过来了,应该是curr_node = *space + i。这是因为您要分配的表达式的值应该在左侧,因为您不能将curr_node 分配给两个变量的总和

这不是你的目的,你也可以这样做*(space + i) = curr_node

【讨论】:

    猜你喜欢
    • 2011-09-03
    • 2018-10-19
    • 1970-01-01
    • 2013-01-27
    相关资源
    最近更新 更多