指针的定义和使用

指针就是用来记录地址的.
语法数据类型 * 指针变量名

#include <iostream>
#include<cmath>
using namespace std;
int main() {
    int a = 10;
    //定义一个指针
    int* p;
    //让指针记录变量a的地址
    p = &a;
    //此处二者地址应该是相同的
    cout << "a的地址为:" << &a << endl;
    cout << "p的值为:" << p << endl;
    //使用指针,通过解引用的方式找到指针指向的内存中的数据
    *p = 20;
    cout << "a的值为:" << a << endl;
    cout << "p的解引用的值为:" << *p << endl;
    return 0;
}

整型的变量要用整型的指针存储,其他的同理.

指针占用的内存大小

#include <iostream>
#include<cmath>
using namespace std;
int main() {
    cout << sizeof(int*) << endl;
    cout << sizeof(float*) << endl;
    cout << sizeof(double*) << endl;
    cout << sizeof(char*) << endl;
    cout << sizeof(short*) << endl;
    return 0;
}

不管什么类型的指针,占用的内存都是相同的,在32位系统下占用4个字节,在64位系统下占用8个字节.

空指针

空指针用于初始化指针变量,空指针指向的内存不可以访问.

#include <iostream>
#include<cmath>
using namespace std;
int main() {
    int* p=NULL;
    //0到255之间的内存编号是系统占用的,运行是会报错,不可访问
    //*p = 100;
    return 0;
}

这里就像我们int a = 0;,我们给一个变量赋初值.给指针赋默认值就是NULL/

野指针

定义:指针变量指向非法的内存空间

#include <iostream>
#include<cmath>
using namespace std;
int main() {
    int* p = (int*)0x1100;
    cout << *p << endl;
    return 0;
}

程序会报错.0x1100 这片地址空间我们不知道它是什么,也没有访问的权限.
总结:空指针和野指针都不是我们申请的空间,因此不要访问。

const修饰指针

  1. const修饰指针---常量指针
  2. const修饰常量---指针常量
  3. const即修饰指针,又修饰常量

常量指针特点:指针的指向可以修改,但
是指针指向的值不可以改

#include <iostream>
#include<cmath>
using namespace std;
int main() {
    int a = 10;
    int b = 20;
    //常量指针
    const int* p = &a;
    //*p = 30; 会报错
    p = &b; // 可以修改指针指向
    return 0;
}

指针常量特点:指针的指向不可以改,指针指向的值可以改

#include <iostream>
#include<cmath>
using namespace std;
int main() {
    int a = 10;
    int b = 20;
    //指针常量
    int* const p = &a;
    *p = 30;//可以修改指针指向的值
    //p = &b; 会报错, 不能修改指针的指向
    return 0;
}

技巧:看const右侧紧跟着的是指针还是常量,是指针就是常量指针,是常量就是指针常量
const既修饰指针,又修饰常量的特点:指针的指向和指针指向的值都不可以修改

#include <iostream>
#include<cmath>
using namespace std;
int main() {
    int a = 10;
    int b = 20;
    const int* const p = &a;
    //*p = 30;不能修改指针指向的值
    //p = &b; 不能修改指针的指向
    return 0;
}

使用指针访问数组

#include <iostream>
#include<cmath>
using namespace std;
int main() {
    int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
    int* p = arr;
    for (int i = 0; i < 10; i++) {
        cout << *(p++) << endl;
    }
    return 0; 
}

指针p++之后会偏移4个字节,也就是指向数组的下一个元素.

指针和函数

#include <iostream>
#include<cmath>
using namespace std;
void swap_test(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
int main() {
    int a = 10, b = 20;
    swap_test(&a, &b);
    cout << "a=" << a << ",b=" << b << endl;
    return 0; 
}

函数在值传递的时候不能修改原本变量的值,但是函数在使用地址传递的时候就可以修改原本变量的值.