2016-10-20 112 views
0

这里是我的代码:作为赋值左操作数所需的左值?

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

} 

“空间”是一个指向就是BEING动态分配的数组。当每个节点被迭代时,我想要在动态分配的数组中存储一个指向该节点的指针,并且保留一个有多少元素的计数。我收到错误消息:'* space + i = curr_node'上的错误消息:

error: lvalue required as left operand of an assignment 

线。

我没有看到它有什么问题。有人可以澄清吗?

UPDATE:

我已经改变了代码,它现在编译,但我得到分段错误当我运行可执行文件。这里是我的代码:

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小菜。

+1

我想你的意思是'*(space + i)= curr_node;' –

+0

@VaughnCato:'*(space + i)'最好写成'space [i]'。 –

回答

1

我相信错误是在这里:

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

i为0会发生什么事,你尝试做(*(space + (i-1)))->name);

您得到space + -1

+0

谢谢你,一个愚蠢的错误。我太专注于内存分配,忘记检查这样的事情。 –

1

预更新的答案:

您似乎已经围绕翻转它,它应该是curr_node = *space + i。这是因为你想分配的表达式的值应该在左边,因为你不能将curr_node分配到两个变量的总和中

这对于你的目的并不完全正确,你可以还做*(space + i) = curr_node

相关问题