版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gongjianbo1992/article/details/77914129
(郁闷,每次改完一看又发现有打错的地方,又改,又审核半天,看来还是不够细心)
指针是保存变量地址的变量。
1.指针基本声明与使用:
using namespace std;
int num = 1;
int *pNum = #
int nums[2] = { 1,2 };
int *pNums = nums;
int *p = new int[10];
*p = 10;
cout << num << ":" << *pNum << endl
<< nums[0] << ":" << *pNums << endl
<< p << ":" << *p << endl;
delete []p;
pNum = 0;
pNums = NULL;
p = nullptr;
2.指针算数:
int *p = new int;
int *p2 = p;
p++;//一个int长度
cout <<p-p2 << endl;
3.指针与数组:
指针与数组的引用方式做了可以“交叉”使用的语法规定,最常见的不同表现在sizeof和&上。
char aChar[10];
cin >> aChar;
cout << aChar << endl;
char *pChar = "what";
//分别输出地址,字符串,首字符:
cout << (int *)pChar << ":" << pChar << ":" << *pChar << endl;
//copy地址;
pChar = aChar;
//copy内容:
pChar = new char[strlen(aChar) + 1];//'\0'
strcpy(pChar, aChar);
//指针与数组下标
int ints[3] = { 1,2,3 };
int *p = ints;
cout << *(p + 1) << endl
<< p[1] << endl
<< ints[1] << endl
<< *(ints + 1) << endl;
4.指针函数:
#define _CRTDBG_MAP_ALLOC//内存监测
#include <iostream>
#include <cstring>
using namespace std;
char *getWord();//原型声明
int main()
{
//1.指针函数的使用
char *word;
word = getWord();
cout << word << ":" << (int *)word << endl;
delete [] word;
word = nullptr;
system("pause");
_CrtDumpMemoryLeaks();
return 0;
}
char * getWord()
{
char temp[50];
cout << "cin a word:";
cin >> temp;
char *p = new char[strlen(temp) + 1];
strcpy_s(p, strlen(temp) + 1,temp);//strcpy vs会报不安全
return p;
}
5.成员访问:
p->name
(*p).name
6.函数指针:
#include <iostream>
int(*pFunc)(int, int);//函数指针
int max(int, int);
int min(int, int);
int main()
{
using namespace std;
pFunc = max;//赋值:函数地址
int num = pFunc(1,2);
cout << num << endl;
pFunc = min;
num = pFunc(1, 2);
cout << num << endl;
system("pause");
return 0;
}
int max(int i, int j)
{
return i > j ? i : j;
}
int min(int i, int j)
{
return i < j ? i : j;
}
7.指针常量与常量指针:
//常量指针:指向常量,不能通过该指针改变指向的值
//但是可以改变指针的指向
int i = 1, j = 2;
const int *cPtr = &i;//or: int const
cPtr = &j;
//*cPtr = 10;错误
//指针常量:不能改变指向,但可以改变指向地址的值
int *const pConst = &i;
*pConst = 10;
//pConst = &j;错误