1.指针与数组的关系
int* pa = x; //x代表数组的首地址
指针+1,实际上是偏移了sizeof(对应数组类型)个字节
#include<iostream>
using namespace std;
int main() {
//指针+1,实际上是偏移了sizeof(对应数组类型)个字节
int x[5] = { 5,4,3,2,1 };
int* pa = x; //x代表数组的首地址
for (int i = 0; i < 5; i++) {
cout << "数组的第 " << (i + 1) << "个元素是" << *pa << endl;
cout << "数组的第 " << (i + 1) << "个元素地址是" << pa << endl;
pa++;
}
cout << "------" << endl;
short y[4] = { 4,3,2,1 };
short* ppa = y;
cout << "第一个元素的地址:" << ppa << endl;
ppa++;
cout << "第二个元素的地址:" << ppa << endl;
cout << "------" << endl;
return 0;
}
2.指针数组
指针数组 存放指针的数组
char a[] = "I";
char b[] = "love";
char c[] = "you";
//指针数组 存放指针的数组
char* p[3];
p[0] = a;
p[1] = b;
p[2] = c;
cout << p[0] << ' ' << p[1] << ' ' << p[2] << endl;
cout << "-------------------" << endl;
int mat[3][4] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
};
int* pmat[3];
pmat[0] = mat[0];
pmat[1] = mat[1];
pmat[2] = mat[2];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << *(pmat[i] + j) << ' '; //pamat[i]为指针指向第i行的首地址,+j表示遍历到第i行的第j个
}
cout << endl;
}
3.数组指针
数组指针 为一个指针
//数组指针 为一个指针
int(*pa)[5];
int x[4][5] = {
{4,3,2,1,0},
{9,8,7,6,5},
{6,7,8,9,0},
{5,6,7,8,9}
};
pa = x;
cout << *(pa) << endl; //E0
cout << pa + 1 << endl; //F4
//偏移20个字节 20 = 4*5 =sizeof(int) *5
cout << pa << ':' << &x[0] << endl;
cout << pa << ':' << &x[1] << endl;
//说明pa存储的某一行地址
4.指针传参
4.1函数的值传递
void swap(int a, int b) {
cout << "调用函数后a的地址 = " << &a << endl;
cout << "调用函数后b的地址 = " << &b << endl;
int temp = a;
a = b;
b = temp;
}
4.2函数的地址传递
void swap(int* a, int* b) {
cout << "调用函数后a的地址 = " << a << endl;
cout << "调用函数后b的地址 = " << b << endl;
cout << "-----------" << endl;
int temp = *a;
cout << "调用函数后a的值 = " << *a << endl;
cout << "调用函数后b的值 = " << *b << endl;
cout << "调用函数后temp的值 = " << temp << endl;
cout << "-----------" << endl;
*a = *b;
cout << "调用函数后a的值 = " << *a << endl;
cout << "调用函数后b的值 = " << *b << endl;
cout << "调用函数后temp的值 = " << temp << endl;
cout << "-----------" << endl;
*b = temp;
cout << "调用函数后a的值 = " << *a << endl;
cout << "调用函数后b的值 = " << *b << endl;
cout << "调用函数后temp的值 = " << temp << endl;
cout << "-----------" << endl;
}
int main() {
int a = 1;
int b = 2;
swap(a, b); //值传递
swap(&a, &b); //地址传递
cout << "调用函数前a的地址 = " << &a << endl;
cout << "调用函数前b的地址 = " << &b << endl;
cout << "-----------" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "-----------" << endl;
return 0;
}