04_C++指针

  1. 指针的定义

#include 
using namespace std;
int main() {

    int a = 10; //定义整型变量a
    int* p;

    //指针变量赋值
    p = &a; //指针指向变量a的地址
    cout << &a << endl; //打印数据a的地址
    cout << p << endl;  //打印指针变量p
    cout << "*p = " << *p << endl;
    system("pause");

    return 0;
}

输出结果:

04_C++指针_第1张图片

定义指针*p以后,p是地址,*p是值

所有指针类型在32位操作系统下是4个字节

  1. const修饰指针

const修饰指针有三种情况

  1. const修饰指针 --- 常量指针

  1. const修饰常量 --- 指针常量

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

#include 
using namespace std;
int main() {

    int a = 5;
    int b = 10;

    //const修饰的是指针,指针指向可以改,指针指向的值不可以更改
    const int* p1 = &a;
    //*p1 = 100;  报错
    cout << *p1 << endl;
    p1 = &b; //正确
    cout << *p1 << endl;

    //const修饰的是常量,指针指向不可以改,指针指向的值可以更改
    int* const p2 = &a;
    //p2 = &b; //错误
    *p2 = 100; //正确
    cout << a << endl;

    //const既修饰指针又修饰常量
    const int* const p3 = &a;
    //p3 = &b; //错误
    //*p3 = 100; //错误

    system("pause");

    return 0;
}
  1. 指针与数组

#include 
using namespace std;
int main() {

    int arr[] = { 1,2,3,4,5,6,7,8,9,10 };

    int* p = arr;  //指向数组的指针

    cout << "第一个元素: " << arr[0] << endl;
    cout << "指针访问第一个元素: " << *p << endl;

    for (int i = 0; i < 10; i++)
    {
        //利用指针遍历数组
        cout << *p << endl;
        p++;
    }

    system("pause");

    return 0;
}

输出结果为:

04_C++指针_第2张图片

总结:指针指向数组时,*p表示的是第一个元素,当P++以后,指针指向下一个元素

  1. 指针与函数

#include 
using namespace std;
void swap2(int* p1, int* p2)
{
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

int main() {

    int a = 10;
    int b = 20;

    swap2(&a, &b); //地址传递会改变实参

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    system("pause");

    return 0;
}

总结:函数参数使用地址传递,函数定义的时候使用指针,调用的时候使用引用。

  1. 指针数组与函数

如下是将数组输出的代码:

#include 
using namespace std;

void printArray(int *arr, int len)
{
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << endl;
    }
}

int main() {

    int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
    int len = sizeof(arr) / sizeof(int);
    printArray(arr, len);
    system("pause");

    return 0;
}

在C++中,函数参数的形式可以使用数组的两种表示方式:使用指针或使用数组

数组名作为函数参数时会自动退化为指针类型,因此,int A[] 和 int* A 作为函数参数是等效的。

例如,下面的两个函数声明是等价的:

void function(int A[]);
void function(int* A);

当调用这个函数时,实参传递的是数组的地址,因此数组名自动转换为指向数组首元素的指针。在函数内部,可以使用指针操作来访问数组中的元素,如 A[i] 或 *(A+i)。

你可能感兴趣的:(C++,c++,开发语言)