在C++中作为函数传递有值传递和地址传递两种。我们一般知道要将一个变量传入函数并希望变量值能发生改变,必须使用地址穿传递,将指向该变量的指针传入。
int num = 1;
int* p = #
void func(int* p)
{
*p = 3;
}
func(p);
cout << num; //3
同样如果是一个指针变量,想要改变它的值也要传入他的指针,才能能够发生值的改变,对于双指针的函数参数一般用于链表创建,二叉树创建等函数,用于返回链表头指针或者二叉树头节点等。以下是是创建二叉树:
typedef struct tn{
int data;
struct tn* LChild;
struct tn* RChild;
}TreeNode;
//visit()为访问函数
int initTree(TreeNode** T)
{
char c;
TreeNode** p = T;
if ((c = getchar()) == '\n')
c = getchar();
if (c == '#')
*p = NULL;
else
{
(*p) = (TreeNode*)malloc(sizeof(TreeNode));
if (!*p)
{
printf("malloc failed");
return 0;
}
(*p)->data = c;
initTree(&(*p)->LChild);
initTree(&(*p)->RChild);
}
return 1;
}
在函数体内涉及到对指针变量值改变的都要用双指针参数,如:
malloc()分配内存等对指针变量重新赋值的。
int* func(int**p)
{
int a[] = { 1, 2, 3, 4, 5, 6 };
p = a;
return p;
}
int**num;
func(num);
对于&运算:
当&和变量类型连用时被称为引用,也就是该变量是另一变量的别名。如:
int a=3;
int &b=a;//b就是a的引用
void func(int &c){c+=1;}
//将a传入,那么变量a的值就会发生改变。
当&与变量名连用时时取地址运算。