54
1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

Embed Size (px)

Citation preview

Page 1: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

1

Chapter 7 Pointers

C/C++ Language Programming

Wanxiang Che

Page 2: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

2

Addressing Method

• 如何读写内存中的数据?– 通过变量的地址访问变量所在的存

储单元• 两种寻址方式

– Direct Addressing• 直接按变量地址来存取变量内容

– Indirect Addressing• 通过指针变量来间接存取它所指

向的变量

0

2000 3 变量 i

2002 6 变量 j

2004 9 变量 k

3010 2000 变量 i_pointer

Page 3: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

3

• Pointer variables, simply called pointers

• Holding memory addresses as their values

• A kind of data type– Normally, a variable contains a specific value,

e.g., an integer, a floating-point value– However, a pointer contains the memory

address of a variable that in turn contains a specific value.

What is a Pointer?

Page 4: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

4

Declare a PointerLike any other variables, pointers must be declared before they can be used. To declare a pointer, use the following syntax:

dataType *pVarName;

For example, the following statement declares a pointer variable named pCount that can point to an int varaible.

int count;int *pCount;pCount = &count;

Address of pCount

Address of variable count Address of variable count

5

pCount count

Page 5: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

5

DereferencingReferencing a value through a pointer is called indirection. The syntax for referencing a value from a pointer is

*pointer

For example, you can increase count using

count++; // direct reference

or

(*pCount)++; // indirect reference

Page 6: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

6

Test Pointer

#include <iostream>using namespace std;

int main() {

int count = 5; int *pCount = &count; cout << "The address of count is " << &count << endl; cout << "The address of count is " << pCount << endl; cout << "The value of count is " << count << endl; cout << "The value of count is " << *pCount << endl; return 0;

}

Page 7: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

7

Pointer Type

Must assign the address of the variable of the same type. It is a syntax error if the type of the variable does not match the type of the pointer. For example, the following code is wrong.

int area = 1;double *pArea = &area; // Wrong

Page 8: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

8

Initializing PointerLike a local variable, a local pointer is assigned an arbitrary value if you don’t initialize it. A pointer may be initialized to NULL, which is a special value for a pointer to indicate that the pointer points to nothing. You should always initialize pointers to prevent errors. Dereferencing a pointer that is not initialized could cause fatal runtime error or it could accidentally modify important data.

e.g.

int *p=NULL;

Page 9: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

9

CautionWe can declare two variables on the same line. For example, the following line declares two int variables:

int i, j;

Can we declare two pointer variables on the same line as follows?

int* pI, pJ;

No, it should be:

int *pI, *pJ;

Page 10: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

10

指针变量与其它类型变量的对比• 共性

– 在内存中占据一定大小的存储单元– 先定义,后使用

• 特殊性– 它的内容只能是地址,而不能是数据– 必须初始化后才能使用,否则指向不确定的存储单元– 只能指向同类型的变量– 可参与的运算:加、减一个整数,指针之间相减,自

增、自减、关系、赋值

Page 11: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

指针运算( 1/3 )• 算术运算• int *p, a[10];

p = a;

p++; /*p 的值增加多少? */• 指针的加减运算是以其指向的类型的字长为单位的

600060016002600360046005600660076008

p-1

p

p+111

Page 12: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

指针运算( 2/3 )• int *p, *q, a[10];p = a;q = &a[5];– q - p – q = p + 3;

• 指针运算不能乱算– 一般只进行指针和整数的加减运算,同类型指针之间

的减法运算– 其它运算,比如乘法、除法、浮点运算、指针之间的

加法等,并无意义,所以也不支持

12

Page 13: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

指针运算( 3/3 )• 关系运算• 只有指向同一种数据类型的两个指针才能进行关系运

算。• 值为 1或 0

– p > q p < q p == q

• 指针不与非指针量进行比较,但可与 NULL(即 0值 ) 进行等或不等的关系运算– 判断 p 是否为空指针– p == NULL– p != NULL

13

Page 14: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

Passing Arguments by Reference with Pointers

There are three ways to pass arguments to a function in C++

•pass by value

•pass by reference with reference

•pass by reference with pointers.

14

Page 15: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

15

main(){ int a, b; a = 15; b = 8; swap(a, b); cout << a << “ “ << b;}

void Swap(int x, int y){ int temp; temp = x; x = y; y = temp;}

1515a b

88

x ya b

x y

Pass by Value

Page 16: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

16

简单变量作函数参数

Swap 函数调用前后参数变化的示意图

15 8 15 8 15 8

15

15 8 8 15 8 15

15

a) 调用 Swap 函数

b) 执行 Swap 函数

c) 从 Swap 函数返回

temp

x y

b

main函数Swap函数

a a a

temp temp

x xy y

b b

Page 17: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

17

main(){ int a, b; a = 15; b = 8; swap(a, b); cout << a << “ “ << b;}

void Swap(int &x, int &y){ int temp; temp = x; x = y; y = temp;}

15a b

8

x ya b

x y

Pass by Reference with Reference Value

Page 18: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

18

main(){ int a, b; a = 15; b = 8; swap(&a, &b); cout << a << “ “ << b;}

void Swap(int *x, int *y){ int temp; temp = *x; *x = *y; *y = temp;}

&a&a &b&b

x ya b

x y15 a b

8

Pass by Reference with Pointers

Page 19: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

19

指针变量作函数参数

用指针变量作函数参数实现两数互换函数的示意图

15 8 8 15

&a &b &a &b

15

(a) 调用 Swap 函数

(b) 执行 Swap 函数

a

a

b

b

*x

*x

*y

*y

y

y

x

x

&a

&b

main函数

Swap函数

temp temp

① ③

Page 20: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

20

指针 swap 函数的几种错误形式( 1 )

• 参数单向传递void Swap(int *p1, int *p2)

{

int *p;

p = p1; /*p1,*p2 为内部变量 */

p1 = p2;

p2 = p;

}

Page 21: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

21

指针 swap 函数的几种错误形式( 2 )

• 指针 p 没有确切地址void Swap(int *p1, int *p2)

{

int *p; /* 指针 p 未初始化 */

*p = *p1;

*p1 = *p2;

*p2 = *p;

}

Page 22: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

22

Arrays and PointersRecall that an array name actually represents the starting address of the array. In this sense, an array variable is essentially a pointer. Suppose you declare an array of int value as follows:

int list[6] = {11, 12, 13, 14, 15, 16};

11 12 13 14 15 16

list[5]

list[4]

list[3]

list[2]

list[1]

list[0]

list+5list+4list+3list+2list+1list

Page 23: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

23

Array Pointer

#include <iostream>using namespace std;

int main() {int list[6] = {11, 12, 13, 14, 15, 16};for (int i = 0; i < 6; i++) cout << "address: " << (list + i) << " " << &list[i] << " value: " << *(list + i) << " " << list[i] << endl;return 0;

}

Page 24: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

24

Pointer with Index

#include <iostream>using namespace std;

int main() {int list[6] = {11, 12, 13, 14, 15, 16};int *pList = &list[0];for (int i = 0; i < 6; i++) cout << "address: " << (pList + i) << " value: " << *(pList + i) << " " << pList[i] << endl;return 0;

}

Page 25: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

指针与数组• 数组名“可以”看作一个指针

– 只是不能修改这个指针的指向• 常指针 int* const

• 指针可当作数组名使用,反之亦然– int *p, a[10];p = a;p[1] = 0;*a = 0;

25

Page 26: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

26

Dynamic Memory Allocation

• Why?– Program Stack is Too Small– Cannot Know the Size of an Array Previously

• Syntax– int *pValue = new int;– int *list = new int[10];

• Allocating Memory from Heap– Reserved until explicitly free

Page 27: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

27

Free Memory

• delete– delete pValue;– delete []list;

• Caution Memory Leak – int *pValue = new int;– *pValue = 10;– int *pValue = new int;

Page 28: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

28

Characters and C-Strings

• A string is a sequence of characters

• There are two ways to process strings– Arrays of characters, pointer-based strings or

C-strings– Using the string class

Page 29: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

29

Character Test Functions Function Description Example

isdigit(c) Returns true if c is a digit. isdigit('7') is true

isdigit('a') is false

isalpha(c) Returns true if c is a letter. isalpha('7') is false

isalpha('a') is true

isalnum(c) Returns true if c is a letter or isalnum('7') is true

a digit. isalnum('a') is true

islower(c) Returns true if c is a lowercase islower('7') is false

letter. islower('a') is true

isupper(c) Returns true if c is an uppercase isupper('a') is false

letter. isupper('A') is true

isspace(c) Returns true if c is a whitespace isspace('\t') is true

character. isspace('A') is false

isprint(c) Returns true if c is a printable isprint(' ') is true

character including space ‘ ‘. isprint('A') is true

isgraph(c) Returns true if c is a printable isgraph(' ') is false

character excluding space ‘ ‘. isgraph('A') is true

ispunct(c) Returns true if c is a printable ispunct('*') is true

character other than a digit, ispunct(',') is true

letter, or space. ispunct('A') is false

iscntrl(c) Returns true if c is a control iscntrl('*') is false

character such as '\n', '\f', '\v', iscntrl('\n') is true

'\a', and '\b'. iscntrl('\f') is true

Page 30: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

30

Case Conversion Functions

Function Description Example

tolower(c) Returns the lowercase equivalent of tolower('A') returns 'a'

c, if c is an uppercase letter. tolower('a') returns 'a'

Otherwise, return c itself. tolower('\t') returns '\t'

toupper(c) Returns the uppercase equivalent of toupper('A') returns 'A'

c, if c is a lowercase letter. toupper('a') returns 'A'

Otherwise, return c itself. toupper('\t') returns '\t'

Page 31: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

31

Storing and Accessing StringsA pointer-based string is an array of characters ending in the null terminator ('\0'), which indicates where a string terminates in memory. A string can also be accessed via a pointer, which points to the first character in the string. So you can declare a string variable using an array or a pointer:

char city[7] = “Harbin"; // Option 1char *pCity = “Harbin"; // Option 2

Page 32: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

32

字符指针变量与字符数组的区别• 定义方法不同

char city[7];

char *pCity;• 赋值方法和含义不同

char city[7];

city = ”Harbin”; /* 错误 */

strcpy(str,”Harbin”); /* 正确 */

char *pCity;

pCity = ”Harbin”;

Page 33: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

33

Array and Pointer SyntaxYou can access city or pCity using the array syntax or pointer syntax. For example,

cout << city[1] << endl;cout << *(city + 1) << endl;cout << pCity[1] << endl;cout << *(pCity + 1) << endl;

each displays character a (the second element in the string).

Page 34: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

34

Reading Strings Read a string from the keyboard using the cin object:

char city[10];char *pCity;

cout << "Enter a city: ";cin >> city; // read to array citycin >> pCity; // Wrongcout << "You entered " << city << endl;

Page 35: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

35

Reading Strings Using getlineC++ provides the cin.getline function in the iostream header file, which reads a string into an array. The syntax of the function is:

cin.getline(char array[], int size, char delimitChar)

The function stops reading characters when the delimiter character is encountered or when the size - 1 number of characters are read. The last character in the array is reserved for the null terminator ('\0'). If the delimiter is encountered, it is read, but not stored in the array. The third argument delimitChar has a default value ('\n').

Page 36: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

36

String

Functions

Function Description

int strlen(char *s1)

Returns the length of the string, i.e., the number of the

characters before the null terminator.

char *strcpy(char *s1, const char *s2)

Copies the string s2 to string s1. The value in s1 is returned.

char *strncpy(char *s1, const char *s2, size_t n)

Copies at most n characters from string s2 to string s1. The

value in s1 is returned.

char *strcat(char *s1, const char *s2)

Appends string s2 to s1. The first character of s2 overwrites the

null terminator in s1. The value in s1 is returned.

char *strncat(char *s1, const char *s2, size_t n)

Appends at most n characters from string s2 to s1. The first

character of s2 overwrites the null terminator in s1 and appends

a null terminator to the result. The value in s1 is returned.

int *strcmp(char *s1, const char *s2)

Returns a value greater than 0, 0, or less than 0 if s1 is greater

than, equal to, or less than s2 based on the numeric code of the

characters.

int *strncmp(char *s1, const char *s2, size_t n)

Returns a value greater than 0, 0, or less than 0 if the n

characters in s1 is greater than, equal to, or less than the first

n characters in s2 based on the numeric code of the characters.

int atoi(char *s1)

Converts the string to an int value.

double atof(char *s1)

Converts the string to a double value.

long atol(char *s1)

Converts the string to a long value.

void itoa(int value, char *s1, int radix)

Converts the value to a string based on specified radix.

Page 37: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

37

String Copy with Char Arrayvoid MyStrcpy(char to[], char from[]){int i = 0; while (from[i] != '\0'){

to[i] = from[i]; i++; } to[i] = '\0';

}

Page 38: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

38

String Copy下标: 0 1 2 3 4 5 6 7 8 9 10 11

H e l l o C h i n a \0

H e l l o C h i n a \0

from[i]

to[i]

下标移动方向

to[i]=‘\0’

from

to

结束拷贝i

i++i

H e l l o C h i n a \0

H e l l o C h i n a \0

*from

*to

指针移动方向

指针移动方向*to=‘\0’to

from++ fromfrom

to++ to

Page 39: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

39

String Copy with Char Pointervoid MyStrcpy(char *to, char *from){while (*from != '\0'){

*to = *from; from++;

to++; }*to = '\0';

}

Page 40: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

40

String Length with Char Arrayunsigned int MyStrlen(char str[]){ int i;unsigned int len = 0; for (i=0; str[i]!='\0'; i++) {

len++; }return (len);

}

Page 41: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

41

String Length with Char Pointerunsigned int MyStrlen(char *pStr){ unsigned int len = 0; for (; *pStr!='\0'; pStr++) {

len++; }return (len);

}

Page 42: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

42

Checking Palindromes

A string is a palindrome if it reads the same forward and backward. The words “mom,” “dad,” and “noon,” for example, are all palindromes.

bool isPalindrome(char * s) { int low = 0; int high = strlen(s) - 1; while (low < high) { if (s[low] != s[high]) return false; low++; high--; } return true;}

Page 43: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

43

String Sort with Two-Dim Char Arraychar str[N][10] = {"Pascal","Basic","Fortran",

"Java","Visual C"};

for (i=0; i<N-1; i++)

{

for (j = i+1; j<N; j++)

{

if (strcmp(str[j], str[i]) < 0)

{

strcpy(temp,str[i]);

strcpy(str[i],str[j]);

strcpy(str[j],temp);

}

}

}

Page 44: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

44

String Sort with Two-Dim Char Array

name[0] P a s c a l \0 \0 \0 \0

name[1] B a s i c \0 \0 \0 \0 \0

name[2] F o r t r a n \0 \0 \0

name[3] J a v a \0 \0 \0 \0 \0 \0

name[4] V i s u a l C \0 \0

strstr

strstr

strstr

strstr

strstr

name[0] B a s i c \0 \0 \0 \0 \0

name[1] F o r t r a n \0 \0 \0

name[2] J a v a \0 \0 \0 \0 \0 \0

name[3] P a s c a l \0 \0 \0 \0

name[4] V i s u a l C \0 \0

strstr

strstr

strstr

strstr

strstr

Page 45: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

45

Array of Pointer

• The elements are pointer• Declare

datatype *array_name[len];• E.g.

char *pStr[5];

pStrpStr [5][5] ** charchar

Page 46: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

46

String Sort with Array of Pointer

char *ptr[N] = {"Pascal","Basic","Fortran", "Java","Visual C"};

for (i=0; i<N-1; i++) { for (j = i+1; j<N; j++) {

if (strcmp(ptr[j], ptr[i]) < 0) { char *temp = ptr[i]; ptr[i] = ptr[j]; ptr[j] = temp; }

} }

Page 47: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

47

指针数组 ptr 字符串排序前 Pascal\0

Basic\0

Fortran\0

Java\0

Visual C\0

ptr[0]

ptr[1]

ptr[2]

ptr[3]

ptr[4]

指针数组 ptr 字符串排序后 Pascal\0

Basic\0

Fortran\0

Java\0

Visual C\0

ptr[0]

ptr[1]

ptr[2]

ptr[3]

ptr[4]

String Sort with Array of Pointer

Page 48: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

48

Command-Line Arguments

• GUI 界面之前,计算机的操作界面都是字符式的命令行界面( DOS 、 UNIX 、 Linux )

• 通过设置命令行参数,用户可以决定程序干什么、怎么干

• int main(int argc, char* argv[])– 当你把 main 函数写成这样时– argc 的值为参数的数目 +1– argv[0] 为指向命令名的字符指针– argv[X](x>0) 为指向每个参数的字符指针

Page 49: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

49

Command-Line Arguments

int main(int argc, char *argv[]){ int i; cout << argc – 1 << " arguments" << endl; for (i = 1; i < argc; i++) cout << i << " " << argv[i];

return 0;}

argv[0]argv[0] echo.exe

argv[1]argv[1]

argv[2]argv[2]

argv[3]argv[3]

programming

is

fun

argv指针数组 字符串

Page 50: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

String Matching

• Given a single keyword p (search string) and an input string s, answer “hit” if p occurs as a substring of s, or “lost” otherwise.

• E.g. – Input

• s = This is a long article ……

• p = article

– Output• hit!

50

Page 51: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

The Brute Force Algorithm

• Search string (pattern): p1p2…pm • Text string: s1s2…sn (usually n >> m)• Compare pattern with the m -character substring sksk+1…

sk+m-1 for each successive value of k from 1 to n - m +1.• The pattern either matches the substring entirely or finds

a position at which the corresponding characters from the pattern and the string don’t match

p1 … pi … pm

s1… sk … sj… sk+m-1 ...

51

Page 52: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

The Brute Force Algorithm

i=0

j=8

i=7

j=14

travel information

informingi=0

j=9

travel information

informing

Conceptually the pattern is shifted

to the right

52

Page 53: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

The Brute Force Algorithm

bool str_search(char s[], char p[]) { int i = 0; int j = 0; int m = strlen(p); int n = strlen(s);

while (i < m && j < n) { if (p[i] == s[j]) { i++; j++; } else { j = j - i + 1; i = 0; } }

return (i >= m) ? true : false;}

53

The loop can stop

earlier: j n - m + 1

at mostn mtimes

Page 54: 1 Chapter 7 Pointers C/C++ Language Programming Wanxiang Che

The Algorithm Performance

54

Worst case Best case Betweentext aaaaaaa abcdefg abababakeyword aab xab abccomparisons (n-m+ 1) * m n-m+ 1

15 5 11

mismatch foundat end of pattern

mismatch foundat beginning of pattern