【问题标题】:Reverse a linked list passing the address of a pointer反转传递指针地址的链表
【发布时间】:2013-05-26 22:52:55
【问题描述】:
typedef struct slist *LInt;

typedef struct slist{

int value;
LInt next;
}Node;

void reverse(LInt *l){

LInt tail;
if(*l){
    tail=(*l)->next;
    reverse(&tail);
    snoc(&tail,(*l)->value);
    free(*l),
    *l=tail;
    }
}

在 main 上,我这样调用函数:reverse(&l); (l 是“LInt l”),snoc 所做的是将值放在列表的最后一个链接。

我的问题是,为什么我们在调用函数时必须传递“l”的地址?为什么在反向的标题上,有“LInt *l”?它是指向我传递的地址的指针吗?

如果这是一个愚蠢的问题,如果我犯了任何语法错误(英语不是我的母语),我很抱歉。

提前谢谢你。

【问题讨论】:

  • 开启警告。 reverse 接受 LInt 并且您将其传递给 LInt*。不一样。

标签: c list pointers linked-list malloc


【解决方案1】:

答案1(为什么我们在调用函数的时候要传递“l”的地址?)

函数reverse() 是假设改变原始列表。但是函数的非数组输入是inputs,它们是按值传递的。它们不会影响原始的l。所以要更改l,您将其地址 传递给reverse()。这允许reverse() 更改l,因为它知道l 的存在位置。

答案2(为什么在reverse的标题上,有“LInt *l”?)

参见答案1。reverse 需要知道LInt 类型的地址 才能影响更改。

例子:

int x,y;   // 2 non-array variables.
y = f(x);  // X does not change.  You expect y to change.
g(&x);     // After g() is done, the value of x may have changed.
           // Of course, the _address_ of x, being what you passed to g(), did not change.

【讨论】:

    【解决方案2】:

    您将 typedef LInt 定义为 POINTER TO STRUCTURE

        typedef struct slist *LInt;            
    

    这就是为什么你不将 'next' 指定为 LInt next;在结构上。

    如果您将 typedef 定义为

        typedef struct slist LInt;
    

    那么传递参数 LInt *l 是有效的。您正在传递一个结构指针。

    Typedef 是为了帮助你创建小的 UNDERSTANDABLE 数据类型(同义词不是新的)

    考虑这样定义:

       typedef struct slist LIST;  //i prefer this mostly
       typedef struct slist * LIST_PTR; 
    

    因此,当您定义新列表时,它不会让您感到困惑。

       LIST *head;  //creating a pointer - Head of linkedlist
       LIST_PTR head;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 2021-09-25
      • 2011-03-19
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多