C 语言的方法传值

最近写链表删除的时候遇到一个问题:

void removeFromLast(node * head)
{
    if(head==NULL)
    {
        printf("have no number");
    }
    if(head->next==NULL)
    {
        head=NULL;
        free(head);
        printf("1\n");
        return;
    }
    node * current=head;
    while(current->next->next!=NULL)
    {
        current=current->next;
    }
    free(current->next);
    current->next=NULL;
}
当我移除最后一个的时候,实际打印的数字一直是第一个数字1211,我是这么添加的:

  node * head;
    head=malloc(sizeof(node));// malloc 函数会返回一个地址,然后将地址赋值一个指针
    head->value=1;
    head->next=NULL;
    pushEnd(head,11);
    pushEnd(head,100);
    pushEnd(head,200);
    node **doublefirst=&head;
    addFirst(1211,doublefirst);

    removeFromLast(*doublefirst);
    printf("va is %d\n",(*doublefirst)->value);
    removeFromLast(*doublefirst);
    removeFromLast(*doublefirst);
    removeFromLast(*doublefirst);
    printf("va is %d\n",(*doublefirst)->value);
    removeFromLast(*doublefirst);
    printf("va is %d\n",(*doublefirst)->value);
    removeFromLast(*doublefirst);
    removeFromLast(*doublefirst);
    printList(*doublefirst);

除了最后一个,剩下的都是移除成功的,why

我了解java 的传引用,明明传过去是地址怎么就不行了,实际上C只有传值这一种方式,地址就是个int值而已,这和传过去一个int i 是没有任何区别的,只不过,通过地址这个值,我们可以改变地址里面的内容,但是,修改一个方法参数并不会改变任何的东西。。。所以,如果想改变将首节点的地址变为null,需要找个二级指针指向这个地址才行。

总结:方法只有传值  

所以改良版的移除操作:

int  removeFromLast(node ** firstlocation){
   node *head=*firstlocation;
    if(head==NULL)
     {
        printf("have no number");
        return 0;
    }
    if(head->next==NULL)
    {
        *firstlocation=NULL;
         free(head);
        return 1;
    }
    node * current=head;
    while(current->next->next!=NULL)
    {
        current=current->next;
    }
    free(current->next);
    current->next=NULL;
    return 0;
}
这样,根据二级指针就能很好的执行删除操作


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值