#include
using namespace std;
int main() {int a = 10; //定义整型变量aint* p;//指针变量赋值p = &a; //指针指向变量a的地址cout << &a << endl; //打印数据a的地址cout << p << endl; //打印指针变量pcout << "*p = " << *p << endl;system("pause");return 0;
}
输出结果:

定义指针*p以后,p是地址,*p是值
所有指针类型在32位操作系统下是4个字节
const修饰指针有三种情况
const修饰指针 --- 常量指针
const修饰常量 --- 指针常量
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;
}
#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;
} 输出结果为:

总结:指针指向数组时,*p表示的是第一个元素,当P++以后,指针指向下一个元素
#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;
} 总结:函数参数使用地址传递,函数定义的时候使用指针,调用的时候使用引用。
如下是将数组输出的代码:
#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)。