地址与指针

在程序中,定义一个变量即可在内存当中开辟一块空间,用于存储这个变量里面的内容

而对于每块空间,都有一个自己的地址,可以使用&变量名的方式获得地址

#include <iostream>

using namespace std;

int main(){
    int a = 5,b = 10;
    cout << "a的地址:" << &a << endl;
    cout << "b的地址:" << &a << endl;
}

a的地址:0x61fe1c
b的地址:0x61fe18

int *p 表示定义一个叫做p的变量,这个变量可以用来保存整数变量的地址,这个p就叫做 指针

因此可以使用指针变量来 保存变量的地址

#include <iostream>

using namespace std;

int main(){
    int a = 5,b = 10;
    int *p,*q;

    p = &a;
    q = &b;

    cout << p << endl;
    cout << q << endl;
}

0x61fe0c
0x61fe08

*是指针操作符。在定义变量时,*p代表变量p定义为指针类型;在使用变量时,*p代表指针变量p中存放的地址所指向的内存单元

#include <iostream>

using namespace std;

int main(){
    int a = 5,b = 10;
    int *p,*q;

    p = &a;
    q = &b;

    cout << *p << endl;
    cout << *q << endl;
}

5
10

普通变量和指针变量的对应关系如下图:

普通变量 Int a指针变量 int *p
&ap
a*p
a = 10*p = 10

练习

下列程序输出的结果是:

#include <iostream>

using namespace std;

int main(){
    char c1,*p1;
    c1 = 'B';
    
    p1 = &c1;
    (*p1) ++ ;

    cout <<  c1 << endl;
}

请编写一程序输出 1-100 的整数,使用指针的方式

#include <iostream>

using namespace std;

int main(){
    int i,*p;
    p = &i;

    for (*p = 1;*p <= 100;(*p)++)
        cout << *p << endl;
}

指针和数组

编写程序,输出数组中的最大值

#include <iostream>

using namespace std;

int main(){
    int a[5] = {5,3,4,7,2};
    int max = 0;
    int *p;

    for (p = a;p < (a+5);p++){
        if (*p > max){
            max = *p;
        }
    }

    cout << max << endl;

}

数组名代表数组首元素的地址,所以a和&a[0]是等价的,如果指针变量p已指向数组中的一个元素,则p+1指向同一数组中的下一个元素

#include <iostream>

using namespace std;

int main(){
    int a[5] = {5,3,4,7,2};
    int *p;

    p = a;

    cout << a << endl;
    cout << p << endl;
}

0x61fe00
0x61fe00

当数组作为参数传递给函数时,函数接受到的实际上是数组的地址,因此在函数中对数组进行操作,实际的数组也会受到影响

#include <iostream>

using namespace std;

void fun(int a[]){  //改变数组的内容
    for (int i = 0;i < 5;i++){
        a[i] = 10;
    }
}

int main(){
    int a[5] = {5,3,4,7,2};
    fun(a);

    //输出结果
    for (int i = 0;i<5;i++){
        cout << a[i] << " ";
    }
}

10 10 10 10 10

课堂练习

请写出下面程序运行的结果:

#include <iostream>

using namespace std;

void swap(int *p1,int *p2){
    int temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

int main(){
    int a[2],*p;
    cin >> a[0] >> a[1];

    p = a;

    swap(p,p++);

    cout << a[0] <<" " << a[1] << endl;
}

课后练习

计算总分:输入四个数字,输出它们的和

输入要求:使用数组存储输入的结果

输出要求:使用指针进行遍历

最后修改:2022 年 03 月 10 日
如果觉得我的文章对你有用,请随意赞赏