编写函数,交换两个int指针

1.值传递,改变只是局限于函数内部,当函数执行完毕后,既不交换指针的本身,即地址,也不交换指针所指的内容

//执行后既不交换指针,也不交换指针所指的内容
swap(int *p,int *q)
{
    int *temp = p;
    p = q;
    q = temp;
}

2.函数内部通过解引用修改指针所指的内容。

//该函数交换指针所指的内容
void swap(int *p,int *q)
{
    int *temp = p;
    *p = *q;
    *q = *temp;
}

3.参数形式是int *&(指针的引用),含义是,该参数是一个引用,(由右向左读),引用对象是int 指针。这样会交换指针本身的值,即地址。

//交换指针本身值,即地址
void swap(int *&p,int *&q)
{
    int *temp = p;
    p = q;
    q = temp;
}

猜你喜欢

转载自blog.csdn.net/qq_38619342/article/details/83544191
今日推荐