指针作为C函数中的参数

jrh*_*4xb 5 c pointers linked-list

在很多例子中我读过一个简单的getListLength()函数看起来像这样:

int getListLength(struct node *head)
{
    struct node *temp = head;
    int iCount = 0;

    while (temp)
    {
        ++iCount;
        temp = temp->next;
    }

    return iCount;
}
Run Code Online (Sandbox Code Playgroud)

让我感到不必要的是声明一个复制传递参数的本地指针(在本例中为*temp).如果我没记错,传递的参数会获得自己的副本.因此,不需要复制*head的本地指针只是因为*head本身就是一个副本,对吗?换句话说,丢弃*temp指针并在任何地方使用head是正确的吗?

cmc*_*cmc 4

是的,它是副本,所以是的,它是正确的。

int getListLength(struct node* head)
{
    int iCount = 0;

    while (head)
    {
        ++iCount;
        head = head->next;
    }
    return iCount;
}
Run Code Online (Sandbox Code Playgroud)

你为什么不亲自执行一下看看呢?