为什么以下 C 代码在链表从内存中释放后不返回 0?

Max*_*ino 0 c free if-statement pass-by-reference pass-by-value

该函数仅在 C 中的链表为空时才删除它。ll_length() 函数已确认有效。如果链表删除成功,则返回0。如果没有删除,则返回负1。该程序返回-1。它输入第一个 if 语句,但不输入第二个。怎么了

ll_destroy(struct linked_list *ll)
{
  if (ll_length(ll) == 0){
    free(ll);
    if (ll == NULL){
      return 0; //remove 0 if removed   
     }
  }
  return -1; // if not deleted
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 6

拨打电话后free

free(ll);
Run Code Online (Sandbox Code Playgroud)

指针的值ll没有改变。指针是按值传递的。也就是说,该函数free处理传递的指针值的副本。所以下一个 if 语句的子语句

if (ll == NULL){
Run Code Online (Sandbox Code Playgroud)

将无法获得控制权。

写吧

  if (ll_length(ll) == 0){
    free(ll);
    return 0; //return 0 if removed   
  }
  return -1; // if not deleted
Run Code Online (Sandbox Code Playgroud)

如果要更改函数调用者中传递的指针,则需要通过引用传递它。例如

int ll_destroy(struct linked_list **ll)
{
  if (ll_length(*ll) == 0){
    free( *ll);
    *ll = NULL;
    return 0;
  }
  return -1; // if not deleted
}
Run Code Online (Sandbox Code Playgroud)

在调用者中你需要写

ll_destroy( &ll );
Run Code Online (Sandbox Code Playgroud)