什么是有说服力的例子,指针运算preferable到数组下标? [英] What are convincing examples where pointer arithmetic is preferable to array subscripting?

查看:138
本文介绍了什么是有说服力的例子,指针运算preferable到数组下标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是preparing一些幻灯片的入门C级,而我试图present很好的例子(和动机)使用指针运算比数组下标。

I'm preparing some slides for an introductory C class, and I'm trying to present good examples (and motivation) for using pointer arithmetic over array subscripting.

很多我在书中看到的例子是相当相当的。例如,许多书籍展示如何扭转字符串中的所有值的情况下,但与带* P上的code是相同更换一个[I]的例外

A lot of the examples I see in books are fairly equivalent. For example, many books show how to reverse the case of all values in a string, but with the exception of replacing an a[i] with a *p the code is identical.

我要寻找与一维数组一个很好的(短)例子,指针运算可以产生显著更优雅code。任何想法?

I am looking for a good (and short) example with single-dimensional arrays where pointer arithmetic can produce significantly more elegant code. Any ideas?

推荐答案

再次获得一个指针,而不是一个值:

人们通常使用指针运算,当他们想再次获得一个指针。要在使用数组索引获得一个指针:你是1)计算指针偏移量,然后2)内存位置所获得的价值,那么3)必须使用与放大器;重新获得该地址。这是更多的打字和不干净的语法。

One usually uses pointer arithmetic when they want to get a pointer again. To get a pointer while using an array index: you are 1) calculating the pointer offset, then 2) getting the value at that memory location, then 3) you have to use & to get the address again. That's more typing and less clean syntax.

例1:比方说,你需要一个指向第512字节的缓冲区

Example 1: Let's say you need a pointer to the 512th byte in a buffer

char buffer[1024]
char *p = buffer + 512;

比清洁剂:

char buffer[1024];
char *p = &buffer[512];

例2:更有效的strcat

Example 2: More efficient strcat

char buffer[1024];
strcpy(buffer, "hello ");
strcpy(buffer + 6, "world!");

这是不是清洁:

char buffer[1024];
strcpy(buffer, "hello ");
strcpy(&buffer[6], "world!");



使用指针算法++作为一个迭代器:

递增与++指针,与递减 - 中元素的数组遍历每个元素时非常有用。它比使用用于跟踪的偏移一个单独的变量吸尘器。

Incrementing pointers with ++, and decrementing with -- is useful when iterating over each element in an array of elements. It is cleaner than using a separate variable used to keep track of the offset.


指针减法:

您可以使用指针减法指针运算。这可以在某些情况下是有用的,让你都指向所述一个之前的元素。它可以与数组下标做太多,但它看起来非常糟糕和混乱。特别是,其中一负标给予索引的东西从列表的末尾蟒程序员。

You can use pointer subtraction with pointer arithmetic. This can be useful in some cases to get the element before the one you are pointing to. It can be done with array subscripts too, but it looks really bad and confusing. Especially to a python programmer where a negative subscript is given to index something from the end of the list.

这篇关于什么是有说服力的例子,指针运算preferable到数组下标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆