2016-10-20 145 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

相關問題