C语言指针二(地址法理解)

江一帆 2020-03-22 PM 3853℃ 0条 2981字 Site load time is:167 ms 百度:已收录

值传递和引用传递

” 按值传递 “中包括值传递(实实在在的值啊!)和指针传递(指针传递参数本质上是值传递的方式,它所传递的是一个地址值),传递的都是实参的一个拷贝。

#include <iostream>
using namespace std;

void swap(int x, int y) {
    int tmp;
    tmp = x;
    x = y;
    y = tmp;
}

int main() {
    int a = 2, b = 3;
    printf("before:%d,%d\n", a, b);
    swap(a, b);
    printf("later:%d,%d\n", a, b);
    return 0;
}

结果:

before:2,3
later:2,3

下面的例子体现了不论传递的是值还是指针 (指针也是一个值),传递给被调用函数的都是实参的一个拷贝,直接对拷贝进行操作不会影响实参

#include <iostream>
using namespace std;

void swap(int *x, int *y) {
    cout<<"函数内-start"<<endl;
    cout<<"*x:"<<*x<<" *y:"<<*y<<endl;
    cout<<"&x:"<<&x<<" &y:"<<&y<<endl;
    cout<<"x:"<<x<<" y:"<<y<<endl;
    cout<<"开始交换"<<endl;
    int *temp= NULL;   //因为x,y的类型都是int *
    temp= x;   //temp= &a   &a:0x61fe1c &b:0x61fe18
    x = y;     // &a= &b
    y = temp;   //&b=temp
    //所以交换x,y只是交换了两者存储的值(值为&a,&b),并没有涉及到主函数a,b值的交换
    //所以只是操作地址并没有卵用
    cout<<"*x:"<<*x<<" *y:"<<*y<<endl;
    cout<<"&x:"<<&x<<" &y:"<<&y<<endl;
    cout<<"x:"<<x<<" y:"<<y<<endl;
    cout<<"函数内-end"<<endl;
}
int main() {
    int a = 2, b = 3;
    cout<<"before a:"<<a<<" b:"<<b<<endl;
    cout << "before &a:" << &a << " &b:" << &b << endl;
    swap(&a, &b);
    cout<<"later a:"<<a<<" b:"<<b<<endl;
    cout << "later &a:" << &a << " &b:" << &b << endl;
    return 0;
}

结果

before a:2 b:3
before &a:0x61fe1c &b:0x61fe18

函数内-start
*x:2 *y:3                   //0x61fe1c->2,0x61fe18->3
&x:0x61fdf0 &y:0x61fdf8
x:0x61fe1c y:0x61fe18   
开始交换
*x:3 *y:2                  //0x61fe1c->2,0x61fe18->3
&x:0x61fdf0 &y:0x61fdf8
x:0x61fe18 y:0x61fe1c
函数内-end

later a:2 b:3
later &a:0x61fe1c &b:0x61fe18

x,y交换.jpg

#include <iostream>
using namespace std;

void swap(int *x, int *y) {
    cout<<"函数内-start"<<endl;
    cout<<"*x:"<<*x<<" *y:"<<*y<<endl;
    cout<<"&x:"<<&x<<" &y:"<<&y<<endl;
    cout<<"x:"<<x<<" y:"<<y<<endl;
    cout<<"开始交换"<<endl;
    int temp;
    //*x作用就是:取指针x的值(&a),再把这个值作为地址,再取这个地址的值!相当于*(&a)=a
    temp= *x;  //temp=a
    *x = *y;   //a=b
    *y = temp;    //b=temp
    cout<<"*x:"<<*x<<" *y:"<<*y<<endl;
    cout<<"&x:"<<&x<<" &y:"<<&y<<endl;
    cout<<"x:"<<x<<" y:"<<y<<endl;
    cout<<"函数内-end"<<endl;
}
int main() {
    int a = 2, b = 3;
    cout<<"before a:"<<a<<" b:"<<b<<endl;
    cout<<"before &a:"<<&a<<" &b:"<<&b<<endl;
    swap(&a, &b);
    cout<<"later a:"<<a<<" b:"<<b<<endl;
    cout<<"later &a:"<<&a<<" &b:"<<&b<<endl;
    return 0;
}

结果:

before a:2 b:3
before &a:0x61fe1c &b:0x61fe18

函数内-start
*x:2 *y:3
&x:0x61fdf0 &y:0x61fdf8
x:0x61fe1c y:0x61fe18
开始交换
*x:3 *y:2
&x:0x61fdf0 &y:0x61fdf8
x:0x61fe1c y:0x61fe18
函数内-end

later a:3 b:2
later &a:0x61fe1c &b:0x61fe18

x,y交换 (2).jpg

标签: none

本文最后更新于:2020-03-23 15:40,可能因经年累月而与现状有所差异。

非特殊说明,本博所有文章均为博主原创。

评论啦~


召唤看板娘