Chapter 3.3 指標 - TKU-ME-Lab/C-C-_tutorial GitHub Wiki
在C++中,有一種變數可以儲存記憶體空間的位址值,稱之為指標變數。 指標變數的宣告語法如下:
資料型態 *指標變數名稱;
資料型態* 指標變數名稱;
下面的敘述,將宣告一個整數指標變數:
int *ptr;
若要一次宣告多個指標變數時,方式如下:
int *ptr1,*ptr2;
欲設定指標變數所儲存位址值,語法如下:
指標變數名稱 = &變數
下面的敘述,將完成value變數宣告,並設定ptr指標變數指向該變數。
int value;
int *ptr;
ptr = &value;
下面的敘述,則在定義指標變數時,就完成起始值的設定,語法如下:
int value;
int *ptr = &value;
下圖將說明ptr指標變數、value變數與*ptr的關係:
請注意!您不可直接將值設定給指標變數,下面的敘述是錯誤的。因為ptr並未起始設定(讓ptr指向某記憶體空間)。
int *ptr;
*ptr = 2; //錯誤,ptr尚未被起始
正確的方式,應該先完成ptr指標變數的起始設定。
int temp;
int *ptr = &temp; //設定ptr指標變數的起始值
*ptr = 2; //此行亦可用temp = 2代替
若要取得指標變數所指向位址的儲存值,則需使用取值運算子 * ,語法如下:
*指標變數名稱
若直接輸出指標變數時,將輸出指標變數儲存的位址值。
cout << 指標變數名稱;
若欲輸出指標變數所指向位址儲存的值時,則必須使用取值運算子。
cout << *指標變數名稱;
int a;
cout << sizeof(a)
取址運算子(address) &
int A=10;
Cout << &A; //顯示出變數A的位址
取值運算子(content) *
cout << *(&A); //顯示出變數A位址上的值
指標(pointer)是一種變數,存放內容為另一變數的位址
int a=100;
int *ptr;
ptr = &a;
cout << a << endl << &a << endl;
cout << *ptr << endl << ptr << endl;
*ptr=10;
cout<<a << endl;
EX:
int *a;
int b = 10;
a = &b;
EX:
int *a , *c;
int b = 10;
a = &b;
c = a;
cout<<c<<endl;
int b = 10;
a = &b;
c=a;
cout<<c<<endl;
螢幕輸出: C3120
EX:
int *a , *c;
int b = 15;
a = &b;
c = a;
cout<<c<<endl;
cout<<*c<<endl;
int b = 15;
a = &b;
c=a;
cout<<c<<endl;
cout<<*c<<endl;
螢幕輸出: E3120
15
EX:
int *a , *c;
int b = -15;a = &b;
c = a;
cout<<b<<endl;
*c = 500;
cout<<*a<<endl;
cout<<*c<<endl;
cout<<b<<endl;
int b = -15;
a = &b;
c = a;
cout<<b<<endl;
螢幕輸出: -15
*c = 500;
cout<<*a<<endl;
cout<<*c<<endl;
cout<<b<<endl;
螢幕輸出: 500
500
500
EX:
int a,b; a = 20; b = 100;
int *c=&a; int *d=&b;
*c = *c * *d;
*d = *c / *d + 20;
cout<<a<<endl;
cout<<b<<endl;
cout<<&b<<endl;
int *c=&a; int *d=&b;
*c = *c * *d;
*d = *c / *d + 20;
cout<<a<<endl;
cout<<b<<endl;
cout<<&b<<endl;
螢幕輸出: 2000
40
E3104
int a = 0;
int *b = &a;
int b;
int *a;
a = 10; //錯誤
a = b; //錯誤
a = &b; //記憶體位置,正確
EX:
char *a = “a pig”;
EX:
char *a[4] = { “Mae”,
“Arnold”,
“Lassie”,
“Greta” };
#include <iostream>
using namespace std;
int main()
{
const char* pstr[] = { "Robert Redford",
"Hopalong Cassidy",
"Lassie",
"Slim Pickens",
"Boris Karloff",
"Oliver Hardy" };
char* pstart = "Your lucky star is ";
int count = (sizeof pstr) / (sizeof pstr[0]);
int dice = 0;
cout << endl
<< " Pick a lucky star!"
<< " Enter a number between 1 and " << count << ": ";
cin >> dice;
cout << endl;
if (dice >= 1 && dice <= count)
cout << pstart << pstr[dice - 1];
else
cout << "Sorry, you haven't got a lucky star.";
cout << endl;
system("pause");
return 0;
}