从零开始的c++学习 5:[指针pointer]

1 minute read

Published:

base on 南科大计算机系课程

lecture05 notes

5.1 pointer

特殊变量, 存的是地址

两个运算符

  • & : 取地址,Operator & can take the address of an object or a variable of fundamental types.

  • * : 取值, 取该指针所指向的地址的值Operator * can take the content that the pointer points to

5.1.1 pointers of pointer

指针的指针

int num = 10;
int * p = #
int ** pp = &p;

5.1.2 Constant pointer 常量指针

指针p所指向的内容(A)不可用使用指针进行修改, 当然.可以直接对那个变量(A)进行修改.

三种类型的 constant

int num = 1;
int another = 2;
//You cannot change the value the p1 points to through p1
const int * p1 = #
*p1 = 3; //error
num = 3; //okay

//You cannot change value of p2 (address)
int * const p2 = #
*p2 = 3; //okay
p2 = &another; //error

//You cannot change either of them
const int* const p3 = #
  • constant pointer 不能赋给普通的pointer

5.2 pointers and Array

对于数组而言,它就是指针, 存的就是地址 对数组取地址,得到的是数组的首地址, 而不是指针的指针 &Array == Array == &Array[0]

5.2. Pointer arithmetic

对指针加减num,则偏移num个元素,而不是地址加减num个字节 ‘假设int类型的指针,对指针±1,相当于偏移4个字节’

  • 这里要注意越界问题

5.2.3 difference

  • 数组相当于constant pointer,
  • The total size of all elements in an array can be got by operator sizeof
  • sizeof operator to a pointer will return the size of the address (4 or 8)
    int numbers[4] = {0, 1, 2, 3};
    int * p = numbers;
    cout << sizeof(numbers) << endl; //4*sizeof(int)
    cout << sizeof(p) << endl; // 4 or 8
    cout << sizeof(double *) << endl; // 4 or 8
    

5.3 - 5.4 c/c++ 分配内存的机制

  • 在实际应用中, 指针的地址都是动态分配的(前面的例子里都是手动赋值)

Program memory

Alt text

动态内存管理

有申请就要有释放, 避免内存泄漏

  • c : malloc and free
  • c++ :
    • new and new[]
    • delete and delete[]