Download presentation
Presentation is loading. Please wait.
1
Introduction to pointers in C/C++
2
Pointers 特殊變數 存放變數在記憶體中的位址 MinGW C++ 中佔用 4 bytes 間接定址取執法 位址 指標變數 變數內容 變數
3
Why pointers? 函數回傳一個以上的值 傳遞陣列或字串參數 建構鏈結相關的資料結構,如 linked list, etc. 記憶體配置函數 malloc() 或 fopen() 等必須使用指 標
4
Declaration 型別 * 變數名稱 ; –int *ptri; –char *ptrch; –float *ptrf=NULL;
5
Operations for pointers &: 位址運算子 *: 依值取值運算子 E.G.: *(&ptri) ptri ++: 指標加法 ( 加上所指型別變數之長度 ) --: 指標減法 ( 減去所指型別變數之長度 ) E.G.: int *ptri; ptri++; /* 將 ptri 的值加 4 */
6
Pointers and Arrays Array variable is a pointer E.G.: int a[3]={1,2,3}; *a a[0] 1 *(a+1) a[1] 2 *(a+2) a[2] a &a[0] a+1 &a[1] a+2 &a[2]
7
Call by value, Call by pointer, and Call by reference (address) int func(int, int) call by value int func(int*, int*) call by pointer Int func(int&, int&) call by reference
8
Call by value 1.// 檔名 :swap1.cpp 2.#include 3.void swap(int, int); 4.main() { 5. int i=3,j=8; 6. cout<<i<<j<<endl; 7. swap(i, j); 8. cout<<i<<j<<endl; 9.} 10.void swap(int a, int b) { 11. int temp=a; 12. a=b; 13. b=temp; 14.}
9
Call by pointer 1.// 檔名 :swap2.cpp 2.#include 3.void swap(int *, int*); 4.main() { 5. int i=3,j=8; 6. cout<<i<<j<<endl; 7. swap(&i, &j); 8. cout<<i<<j<<endl; 9.} 10.void swap(int* a, int *b) { 11. int temp=*a; 12. *a=*b; 13. *b=temp; 14.}
10
Call by pointer 1.// 檔名 :swap3.cpp 2.#include 3.void swap(int &, int&); 4.main() { 5. int i=3,j=8; 6. cout<<i<<j<<endl; 7. swap(i, j); 8. cout<<i<<j<<endl; 9.} 10.void swap(int& a, int &b) { 11. int temp=a; 12. a=b; 13. b=temp; 14.}
11
Pointer of pointer 1.int i=5, *a, **b; 2.a=&i; 3.b=&a; What is the value of –*a –a –&a –**b –*b –b –&b
12
Q&A
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.