双指针

对于C语言的参数传递都是值传递,当传递一个指针给函数的时,其实质上还是值传递,除非使用双指针。

void  swap ( int *a, int *b ){  
    int c;  
    c = *a;  
    *a = *b;  
    *b = c;  
}  
int  main(void){  
    int a,b;  
    a = 1;  
    b = 2;  
    swap( &a, &b);  
    return 0;  
} 

上面例子,a,b能进行交换。

swap函数中a和b是分别是main函数中a和b的地址,在swap函数中,使用*号分别对a和b进行解引用,

所以在swap函数中对*a和*b的操作就等于操作main函数中的a和b。


在看下面的例子:

void swap ( int *a, int *b ){  
    int *temp;  
    temp = NULL;  
    temp = a;  
    a = b;  
    b = temp;   
}  
int main (void){  
    int a,b;  
    a = 1;  
    b = 2;  
    swap(&a, &b);  
    return 0;  
}  

上面的例子,a,b不能进行交换。

swap函数中,没有对a和b进行解引用,所以a和b只是swap函数的局部变量,是main函数中a和b的副本,

在swap中对a和b进行操作,不会对反映到main中去。


typedef struct node{  
    int  n;
}list;  

void createList(list *head){
   head = (list*)malloc(sizeof(list));  
}

int main(void){
    list *head = NULL;
    createList(head);
	if(head != NULL){
		free(head);
		head = NULL;
	}
}

上面的例子中,最后head的值还是NULL。


要想使head的值为head被赋值,必须使用双重指针。

typedef struct node{  
    int  n;
}list;  

void createList(list **head){
   *head = (list*)malloc(sizeof(list));  
}

int main(void){
    list *head = NULL;
    createList(&head);
	if(head != NULL){
		free(head);
		head = NULL;
	}
}
上面的例子中,最后head指向了node。

那么二重指针是如何对main中的head赋值的呢?

main函数中的head类型为list*,&head类型为list**,对createList中的head进行解引用后(*head)进行赋值,

就是对main中head进行赋值(类型为list*)。


最后总结一下:

如果要对指针指向的值进行修改,可以直接传指针。

如果要对指针自身的值进行修改,就要使用双指针。

#include <stdio.h>
#include <malloc.h>

typedef struct st_data{
        int n;
}data;

void changeValue1(data* d){
        d->n = 2;
}

void changeValue2(data* d){
        d = NULL;
}

void changeValue3(data* d){
        d = (data*)malloc(sizeof(data));
}

int main(void){
        data* d = (data*)malloc(sizeof(data));
        d->n = 1;
        printf("d->n=%d\n",d->n);
        changeValue1(d);
        printf("d->n=%d\n",d->n);

        if(d == NULL){
                printf("d is NULL\n");
        }else{
                printf("d is not NULL\n");
        }
        changeValue2(d);
        if(d == NULL){
                printf("d is NULL\n");
        }else{
                printf("d is not NULL\n");
        }
        free(d);

        d = NULL;
        if(d == NULL){
                printf("d is NULL\n");
        }else{
                printf("d is not NULL\n");
        }
        changeValue3(d);
        if(d == NULL){
                printf("d is NULL\n");
        }else{
                printf("d is not NULL\n");
        }

        return 0;
}

运行结果为:

d->n=1
d->n=2
d is not NULL
d is not NULL
d is NULL
d is NULL



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值