1 / 12

Introduction to pointers in C/C++

Introduction to pointers in C/C++. Pointers. 特殊變數 存放變數在記憶體中的位址 MinGW C++ 中佔用 4 bytes 間接定址取執法. 變數. 指標變數. 變數內容. 位址. Why pointers?. 函數回傳一個以上的值 傳遞陣列或字串參數 建構鏈結相關的資料結構,如 linked list, etc. 記憶體配置函數 malloc() 或 fopen() 等必須使用指標. Declaration. 型別 *變數名稱 ; int *ptri; char *ptrch;

jalene
Download Presentation

Introduction to pointers in C/C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to pointersin 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 • //檔名:swap1.cpp • #include <iostream.h> • void swap(int, int); • main() { • int i=3,j=8; • cout<<i<<j<<endl; • swap(i, j); • cout<<i<<j<<endl; • } • void swap(int a, int b) { • int temp=a; • a=b; • b=temp; • }

  9. Call by pointer • //檔名:swap2.cpp • #include <iostream.h> • void swap(int *, int*); • main() { • int i=3,j=8; • cout<<i<<j<<endl; • swap(&i, &j); • cout<<i<<j<<endl; • } • void swap(int* a, int *b) { • int temp=*a; • *a=*b; • *b=temp; • }

  10. Call by pointer • //檔名:swap3.cpp • #include <iostream.h> • void swap(int &, int&); • main() { • int i=3,j=8; • cout<<i<<j<<endl; • swap(i, j); • cout<<i<<j<<endl; • } • void swap(int& a, int &b) { • int temp=a; • a=b; • b=temp; • }

  11. Pointer of pointer • int i=5, *a, **b; • a=&i; • b=&a; • What is the value of • *a • a • &a • **b • *b • b • &b

  12. Q&A

More Related