对于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