CRITICAL SKILL 4.11: Pointers and Arrays 指针和数组

来源:互联网 发布:手机淘宝怎么举报商品 编辑:程序博客网 时间:2024/05/08 13:40

CRITICAL SKILL 4.11: Pointers and Arrays 指针和数组

In C++, there is a close relationship between pointers andarrays. In fact, frequently a pointer and an array are interchangeable.Consider this fragment:

char str[80]; char *p1;

p1 = str;

Here, str is an array of 80 characters and p1 is a characterpointer. However, it is the third line that is of interest. In this line, p1 isassigned the address of the first element in the str array. (That is, after theassignment, p1 will point to str[0].) Here’s why: In C++, using the name of anarray without an index generates a pointer to the first element in the array.Thus, the assignment

p1 =str;

assigns the address of str[0] to p1. This is a crucial pointto understand: When an unindexed array name is used in an expression, it yieldsa pointer to the first element in the array. Since, after the assignment, p1points to the beginning of str, you can use p1 to access elements in the array.For example, if you want to access the fifth element in str, you can use

str[4]or *(p1+4)

Both statements obtain the fifth element. Remember, arrayindices start at zero, so when str is indexed, a 4 is used to access the fifthelement. A 4 is also added to the pointer p1 to get the fifth element, becausep1 currently points to the first element of str.

 

The parentheses surrounding p1+4 are necessary because the *operation has a higher priority than the + operation. Without them, theexpression would first find the value pointed to by p1 (the first location inthe array) and then add 4 to it. In effect, C++ allows two methods of accessingarray elements: pointer arithmetic and array indexing. This is importantbecause pointer arithmetic can sometimes be faster than arrayindexing—especially when you are accessing an array in strictly sequentialorder. Since speed is often a consideration in programming, the use of pointersto access array elements is very common in C++ programs. Also, you cansometimes write tighter code by using pointers instead of array indexing.

 

Here is an example that demonstrates the difference betweenusing array indexing and pointer arithmetic to access the elements of an array.We will create two versions of a program that reverse the case of letterswithin a string. The first version uses array indexing. The second uses pointerarithmetic. The first version is shown here:

>>>>>>在c++里,指针和数组是紧密相关的。实际上,指针和数组相互之间经常是可交换的。思考这个码片:

charstr[80]; char *pl;

pl =str;

这里,str是一个带有80字符空间的数组,pl是一个字符指针。不管怎样,第三行才是我们关心的。在这行pl被赋值为数组str的第一个元素的地址。(赋值之后的结果是pl指向第数组元素str[0])在c++里面,指针在使用不带数组索引的数组名的时候,会指向数组的的一个元素。因此这个分配(赋值):pl = str;,赋数组的第一个元素str[0]给pl。这是要理解的关键点:当一个未索引的数组名在表达式里面出现的时候,他会指向数组的第一个元素。所以,在赋值以后,pl执行str的开头,之后可以用pl访问数组里面的元素。如:如果要访问str数组的第五个元素,可以使用str[4]或者*(pl+4)。两条指令都是访问第五个元素。勤记,数组从0开始索引,所以在str索引时,4就表示索引第五个元素。对一个指针来说加4会获得第五个元素(指针指向的),在此由于pl当前指向str的第一个元素。

       因为*操作符比+操作符优先级高,所以pl+4外面的()是必须的。如果没有的话,表达式首先找到pl指向的值(数组第一个位置的值),然后给这个值加上4。实际上,c++在允许两种方式访问数组元素:指针运算(如+4)和数组索引(str[4])。这是重点,因为指针运算通常比数组索引要快,尤其是在完全的时序访问一个数组的时候。由于在编程的时候速度是经常考虑的因素,所以在c++里使用指针来访问数组是非常通用(常用的)。并且,使用指针代替数组,有时候写出来的代码比较的紧凑。

       以下example演示在访问数组元素的时候,在使用数组索引和指针访问的一个差别。此处会创建字符串里字符转换的两个版本代码。第一个使用数组索引。第二个是使用指针运算。

Version 1 array index example:

#include <iostream>

#include <cctype>

/*

cctypeheadfile included functions:êoisalnum/isalpha/isblank/iscntrl/isdigit/isgraph/

                   islower/isprint/ispunct/isspace/isupper/isxdigit/tolower/toupper;

you canbrowse the declaration in the headfile and implement of each functionw will bein *.cpp file or

in lib'sfile

*/

using namespace std;

int main()

{                

         int i;

         charstr[80] = "This Is A Test";

         cout<<"Originalstring:"<<str<<'\n';

         for(i =0;str[i];i++)

         {

                   if(isupper(str[i]))

                            str[i] =tolower(str[i]);

                   elseif (islower(str[i]))

                            str[i] =toupper(str[i]);

         }

         cout<<"Inverted-casestring:"<<str;

 

         return0;

}

The output from the program is shown here:

Notice that the program uses the isupper( ) and islower( )library functions to determine the case of a letter. The isupper( ) functionreturns true when its argument is an uppercase letter; islower( ) returns truewhen its argument is a lowercase letter. Inside the for loop, str is indexed,and the case of each letter is checked and changed. The loop iterates until thenull terminating str is indexed. Since a null is zero (false), the loop stops.

>>>>>>第一个版本如上version1 array index;

输出结果

留心使用isupper()和islower()库函数来检测字母的大小写。isupper()函数的参数如果是大些的话返回值为真true;islower()函数的参数如果是小写的话返回值是true。循环体里面索引str,没检测到一个字母都会做出改变(tolower/toupper转换)。重复循环,直到str索引到null空结束符。因为null是0(false),循环就会结束。

 

Version 2 is use the pointer access  example:

#include <iostream>

#include <cctype>

/*cctypeheadfile included functions:êoisalnum/isalpha/isblank/iscntrl/isdigit/isgraph/

                   islower/isprint/ispunct/isspace/isupper/isxdigit/tolower/toupper;

you canbrowse the declaration in the headfile and implement of each functionw will bein *.cpp file or

in lib'sfile*/

using namespace std;

int main()

{                

         int i;

         char*p;

         charstr[80] = "This Is Test For AnotherVersion";

         p = str;

         cout<<"Originalstring:"<<str<<'\n';

         for(;*p;p++)

         {

                   if(isupper(*p))

                            *p = tolower(*p);

                   elseif (islower(*p))

                            *p = toupper(*p);

         }

         cout<<"Inverted-casestring:"<<str;

         return0;

}

Output of thisprogrogram is :

>>>>>>第二个版本如上>>>>>

Indexing a Pointer  用指针索引

As you have just seen, it is possible to access an arrayusing pointer arithmetic. What you might find surprising is that the reverse isalso true. In C++, it is possible to index a pointer as if it were an array.Here is an example. It is a third version of the case-changing program.

Version 3:

#include <iostream>

#include <cctype>

using namespace std;

int main()

{                

         int i;

         char*p;

         charstr[80] = "This Is 3Td Version";

         p = str;

         cout<<"Originalstring:"<<str<<'\n';

         for(i =0;p[i];i++)

         {

                   if(isupper(p[i]))

                            p[i] =tolower(p[i]);

                   elseif (islower(p[i]))

                            p[i] =toupper(p[i]);

         }

         cout<<"Inverted-casestring:"<<str;

         return0;

}

The program creates a char pointer called p and then assignsto that pointer the address of the first element in str. Inside the for loop, pis indexed using the normal array indexing syntax. This is perfectly validbecause in C++, the statement p[i] is functionally identical to *(p+i). Thisfurther illustrates the close relationship between pointers and arrays.

>>>>>>指针索引:

如之前所见,使用指针运算来访问数组时可行的。可能会惊奇的发现转换也是可行的。C++里,索引一个指针就像这个指针是数组一样也是可行的。Example 3,用于大小写转换代码:

代码如上所示>>>>>><<<<<<

       代码创建了一个指针p,然后把数组str的第一个元素赋给她。再循环体内部,p使用数组索引的语法来索引。在c++里面这是完全有效地,指令p[i]功能上等同于*(p+i)。之后还会有关于指针和数组紧密关系的阐述。

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Translatedby 欧阳军

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Email:ouyangjun1985@msn.com

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>QQ:724106475

原创粉丝点击