指针
基本概念
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include <iostream> #include <string> using namespace std; int main() { int a = 10; int * p; p = &a; int *p = &a; cout << "a的地址是:" << &a << endl; cout << "指针p是:" << p << endl; cout << "*p=" << *p << endl; *p = 1000; cout << "a=" << a << endl; cout << "p=" << p << endl; cout << "*p=" << *p << endl; int b = 5; int * p1 = &b; cout << sizeof(p1) << endl; cout << sizeof(int*) << endl; cout << sizeof(float*) << endl; cout << sizeof(double*) << endl; cout << sizeof(char*) << endl; int *p2 = nullptr; int *p3 = (int *)0x1100; int a1 = 4; int a2 = 9; const int *p4 = &a1; p4 = &a2; int * const p5 = &a1; *p5 = 10; const int * const p6 = &a1; int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; int *p7 = arr; cout << *p7 << endl; p7++; cout << *p7 << endl; int *p8 = arr; for (int i = 0; i < 10; i++) { cout << *p8 << endl; p8++; } system("pause"); return 0; }
|
💭注:nullptr
是在C++11引入的一个特殊的字面值,用来安全高效地表示空指针,避免了C语言风格中将 NULL
或 0
用作空指针时可能出现的错误。在 int *p2 = nullptr;
这行代码中,p2
被初始化为指向空对象的指针。这在编程中是一种常见的做法,确保指针在未被正确初始化之前不会访问任何对象,可以避免运行时错误。nullptr
与 NULL
不同,NULL
通常被定义为 0
的宏,而 nullptr
是精确的空指针。
const
在 *
的位置:左定值,右定向。
函数的地址传递
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <iostream> #include <string> using namespace std;
void swap(int *p1, int *p2) { int temp = *p1; *p1 = *p2; *p2 = temp; }
int main() { int a = 10; int b = 20; swap(&a, &b); cout << "a=" << a << endl; cout << "b=" << b << endl; system("pause"); return 0; }
|
结构体
基本概念
1 2 3 4 5 6 7
| struct Student { string name; int age; int score; }S3;
|