1、指针的定义和使用
#include <iostream> using namespace std; int main() { int a = 10; int* p; p = &a; cout << "a的地址为:" << &a << endl; cout << "a的地址为:" << p << endl; *p = 1000; cout << "a = " << a << endl; cout << "*p = " << *p << endl; system("pause"); return 0; }
2、指针所占内存空间
#include <iostream> using namespace std; int main() { int a = 10; int* p = &a; //在32位操作系统下,指针是占4个字节空间大小,不管是什么数据类型 //在64位操作系统下,指针是占8个字节空间大小,不管是什么数据类型 cout << "指针占内存的大小:" << sizeof(int *) << endl; cout << "指针占内存的大小:" << sizeof(p) << endl; cout << "指针占内存的大小:" << sizeof(char *) << endl; cout << "指针占内存的大小:" << sizeof(float *) << endl; cout << "指针占内存的大小:" << sizeof(double *) << endl; system("pause"); return 0; }
3、空指针和野指针
#include <iostream> using namespace std; int main() { //空指针 int* p = NULL; //野指针 尽量避免野指针 int* p = (int*)0x1100; system("pause"); return 0; }
4、const修饰指针
#include <iostream> using namespace std; int main() { //1、const修饰指针 常量指针 //指针指向的值不可以改,指针的指向可以改 int a = 10; int b = 10; const int* p = &a; //*p=20; 错误 p = &b;//正确 //2、const修饰常量 指针常量 //指针的指向不可以改,指针指向的值可以改 int* const p2 = &a; *p2 = 100;//正确 //p2 = &b;错误 //3、const修饰指针和常量 //指针的指向和指针指向的值都不可以改 const int* const p3 = &a; //*p3 = 100;错误 //p3 = &b;错误 system("pause"); return 0; }
5、指针和数组
#include <iostream> using namespace std; int main() { int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; int* p = arr; cout <<"利用指针访问第一个元素:"<< * p << endl; p++; cout << "利用指针访问第二个元素:" << *p << endl; int* p2 = arr; for (int i = 0; i < 10; i++) { cout << *(p2 + i) << endl; } system("pause"); return 0; }
6、指针和函数
#include <iostream> 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; }
7、案例
案例描述:封装一个函数,利用冒泡排序,实现对整型数组的升序排序例如数组: int arr[10] ={ 4,3,6,9,1,2,10,8,7,5} ;
#include <iostream> using namespace std; void bubbleSort(int * arr,int len) { for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } void printfArray(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(arr[0]); bubbleSort(arr,len); printfArray(arr, len); system("pause"); return 0; }