CSC3002【C++指针】
一,memory
①每一个byte都有一个地址
②xbit的machine的地址长度都是x
③类比:
|
Hotel |
Memory |
|
Bed |
Bit |
|
Room |
Byte |
|
Floor |
Word |
|
Room number |
Address |
|
Number of rooms |
Memory size |
|
Extended-stay rooms |
Static |
|
Rooms sold offline |
Heap |
|
Rooms booked online |
Stack |
二,编译器
编译器会记住variable的名字和address的对应关系
三,指针
A data item whose value is an address in memory is called a pointer, which can be manipulated just like any other kind of data.
double total=10
double* pTotal=& total//前面的type指的是total的type
//pTotal是指针而不是*pTotal
C++ includes two built-in operators for working with pointers:
The address-of operator (&) is written before a variable name (or any expression to which you could assign a value, an lvalue) and returns the address of that variable.
The value-pointed-to operator (*) is written before a pointer expression and returns the actual value of a variable to which the pointer points (dereferencing).

(*p1=17)指的是拿到p1里面的value所对应的地址并且读取地址所对应的数值
四,指针和引用的区别
|
Pointer |
Reference |
|
|
Definition |
The memory address of an object |
An alternative identifier for an object |
|
Declaration |
int i = 5; int * p = &i; |
int i = 5; int & r = i; |
|
Dereferencing |
*p |
r |
|
Has an address |
Yes (&p) |
No (the same as &i) |
|
Pointing/referring to nothing |
Yes (NULL/ nullptr since C++11) |
No |
|
Reassignments to new objects |
Yes |
No |
|
Supported by |
C and C++ |
C++ |
五,有关指针的细节(类)
Point pt(3, 4);
Point * pp = &pt;
pt.getX();
(*pp).getX();
pp->getX();
六,有关指针的示例
函数返回一个指针(返回最大值的地址)
// 定义一个函数 max,接受两个 int 类型的指针参数 a 和 b
int* max(int* a, int* b) {
// 如果 a 指向的值大于 b 指向的值(通过解引用 *a 和 *b 获取值)
if (*a > *b)
return a; // 返回 a(即返回较大值所在变量的地址)
else
return b; // 否则返回 b(即返回另一个的地址)
}
int main() {
int x = 10, y = 20; // 声明两个 int 类型变量,x = 10,y = 20
// 调用 max 函数,传入 x 和 y 的地址,函数返回较大者的地址,赋值给指针 p
int* p = max(&x, &y);
// 解引用 p,获取它指向的值(也就是 x 或 y 中较大的那个),并输出
cout << *p << endl; // 输出:20,因为 y 的值比较大,p == &y,*p == 20
}
更多推荐



所有评论(0)