陣列和指標

小弟季義欽發表於2012-11-02
#include <iostream>

using namespace std;

void testPointer(){
	int a[] = {1,2,3,4,5};
	int *p = a;		//本身就是int型指標
//	int *q = &a;	//轉換成int型指標
	int *t = &a[0];	//本身就是int型指標
	p++;
//	q++;
	t++;
	printf("*p:%d\n",*p);	//2
//	printf("*q:%d\n",*q);	//2
	printf("*t:%d\n",*t);	//2
}

void testPointer2(){
	int a[] = {1,2,3,4,5};
	int *p = a+1;	//一維陣列陣列名字a表示陣列中第一個元素(int)的地址
//	int *q = &a+1;	//在轉換成int型指標之前的+1操作被解釋為陣列的長度
	int *w = &a[0]+1;	
	printf("%d\n",*p);		//2
//	printf("%d\n",*(q-1));	//5
	printf("%d\n",*w);		//2
}

void testPointer3(){
	int a[] = {1,2,3,4,5};
	const int *p = a;	//指向的元素是const int
	int const *q = a;	//和前者相同
	int *const t = a;	//const的指標,指向int
	p++;
	//(*p)++;	//compile error
	q++;
	//(*q)++;	//compile error
	(*t)++;
	//t++;		//compile error
}

void testPointer4(){
	int a[4][4] = {  
                  {1,2,3,4},  
                  {50,60,70,80},  
                  {900,1000,1100,1200},  
                  {13000,14000,15000,16000} }; 
	int (*p1)[4] = a;		//指標陣列,
	int (*p2)[4] = &a[0];	//指標陣列,分別指向陣列a[0],a[1]...的地址
    int *p3 = &a[0][0];		//第一個元素的地址
	//陣列p1的大小是4,所以是*(p3+1)
	cout<<*(p3+sizeof(p1)-3)<<endl;	//2

	//p2指向第一個陣列a[0],減一就指向前一個陣列的地址,*(&a[-1])就變成
	//前一個陣列的第一個元素的地址,+16就變成13000的地址了。
	cout<<*(*(p2-1)+16)+2<<endl;	//13002

	//p1也是指標陣列,指向a[0]的地址,然後+3就是指向a[3]的地址
	//*(&a[3])就變成了a[3]的第一個元素的地址,-2變成1100的地址
	cout<<*(*(p1+3)-2)+1<<endl;		//1101

	//一維陣列陣列名代表一個元素的地址,二維陣列陣列名代表第一個子陣列的地址
	//所以a+1代表a[1]的地址,然後*(&a[1])代表a[1]的第一個元素的地址。-1變成4的地址。
	cout<<*(*(a+1)-1)<<endl;		//4
}

int main(){
	testPointer();
	testPointer2();
	testPointer3();
	testPointer4();
	return 0;
}

相關文章