1. 程式人生 > >C++基礎學習筆記:指標

C++基礎學習筆記:指標

(鬱悶,每次改完一看又發現有打錯的地方,又改,又稽核半天,看來還是不夠細心)

指標是儲存變數地址的變數。

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;錯誤