Pointer
คือการชี้ไปยังตำแหน่งของตัวแปรชนิดนั้นๆอยู่
char* p = &c; //p จะบอกตำแหน่งของ c; เครื่องหมาย & เป็นการบอกตำแหน่ง
char c2 = *p; // c2 = ‘a’;
ความหมาย pointer แบบต่างๆ
int* pi; //pointer to int
char** ppc; // pointer to pointer to char
int* ap[15]; //array of 15 pointer to ints
int (*fp)(char*) //pointer to function taking a char* argument; returns an int
int* f(char*) //function taking a char* argument; returns a pointer to int
void*
“Pointer to an object of unknown type” ในบางครั้งเราอาจจำเป็นต้องเก็บค่าหรือส่งค่าจาก address of memory ที่ไม่แน่ใจว่าเป็นตัวแปรชนิดไหน
pointer ทุกชนิดสามารถ assign เป็น void* ได้ (ยกเว้น pointer to function, pointer to member)
void* สามารถ
- assign to another void*
- comparable (=, !=)
- explicitly converted to another type
void pf(int* pi)
{
void* pv = pi; //implicit conversion of int* to void*
int* pi2 = static_cast(pv); //explicit conversion back to int*
double* pd3 = static_cast(pv); //unsafe
cout << "pi= " << *pi << "\taddress = " << &pi << "\t addr of i = " << pi << "\n";
cout << "pv= " << pv << "\taddress = " << &pv << "\t addr of i = " << pv << "\n"; //*pv ไม่่สามารถแสดงผลได้ จึงแสดงตำแหน่ง pv แทน
cout << "pi2=" << *pi2 << "\taddress = " << &pi2 << "\t addr of i = " << pi2 << "\n";
cout << "pd3=" << *pd3 << "\taddress = " << &pd3 << "\t addr of i = " << pd3 << "\n";
}
int main()
{
int i = 25;
pf(&i);
cout << "i=" << i << "address of i =" << &i << "\n";
}
แสดงผล
pi= 25 address = 003EFAE0 addr of i = 003EFBB4
pv= 003EFBB4 address = 003EFACC addr of i = 003EFBB4
pi2=25 address = 003EFAC0 addr of i = 003EFBB4
pd3=-9.25596e+61 address = 003EFAB4 addr of i = 003EFBB4
i=25 address of i =003EFBB4
