C++基础学习笔记:指针

来源:互联网 发布:u9数据字典怎么用 编辑:程序博客网 时间:2024/06/01 23:59

(郁闷,每次改完一看又发现有打错的地方,又改,又审核半天,看来还是不够细心)

指针是保存变量地址的变量。

1.指针基本声明与使用:

 using namespace std; int num = 1; int *pNum = &num; 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 constcPtr = &j;//*cPtr = 10;错误//指针常量:不能改变指向,但可以改变指向地址的值int *const pConst = &i;*pConst = 10;//pConst = &j;错误




原创粉丝点击