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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 JavaScript 编写的打砖块游戏(附源代码)   项目:JavaScript 打砖块游戏(附源代码) 打砖块游戏是使用 HTML5、CSS 和 JavaScript 开发的简单项目。这款游戏是关于借助弹跳球和滑动平面来打破障碍。您可以玩游戏,直到能够打破所有砖块而不会将球掉到地上。玩家必须使用箭头键移动滑动平面。 游戏制作 该项目仅包含 HTML、CSS 和 JavaScript。谈到这款游戏的功能,用户必须移动滑动平面以使球反弹回来以打破砖块。球必须接触砖块才能将其打破,并且不应掉落到地上。这款游戏的 PC 控制也很简单。您只需使用左、右、上、下键根据要求移动滑动平面即可。如果玩家能够在 3 次生命中清除所有砖块,则获胜。 该游戏包含大量的 javascript 以确保游戏正常运行。 如何运行该项目? 要运行此游戏,您不需要任何类型的本地服务器,但需要浏览器。我们建议您使用现代浏览器,如 Google Chrome 和 Mozilla Firefox, 以获得更好、更优化的游戏体验。要玩游戏,首先,单击 index.html 文件在浏览器中打开游戏。 演示: 该项目为国外大神项目,可以作为毕业设计的项目,也可以作为大作业项目,不用担心代码重复,设计重复等,如果需要对项目进行修改,需要具备一定基础知识。 注意:如果装有360等杀毒软件,可能会出现误报的情况,源码本身并无病毒,使用源码时可以关闭360,或者添加信任。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值