说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C2-C_depth/advanced_pointer_arithmetic.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
2.9.4. Pointer Arithmetic
如果一个指针变量指向一个数组,程序就可以对该指针进行运算,来访问数组中的任意元素。在大多数情况下,我们不建议用指针运算访问数组元素:这样做容易出错,出错后也更难调试。不过,有时依次递增一个指针来遍历数组元素会比较方便。
If a pointer variable points to an array, a program can perform arithmetic on the pointer to access any of the array’s elements. In most cases, we recommend against using pointer arithmetic to access array elements: it’s easy to make errors and more difficult to debug when you do. However, occasionally it may be convenient to successively increment a pointer to iterate over an array of elements.
指针递增后,会指向它所指类型的下一个存储位置。例如,递增一个整型指针(int *)会让它指向下一个 int 存储地址(比当前值多 4 字节的地址),递增一个字符指针会让它指向下一个 char 存储地址(比当前值多 1 字节的地址)。
When incremented, a pointer points to the next storage location of the type it points to. For example, incrementing an integer pointer (
int *) makes it point to the nextintstorage address (the address four bytes beyond its current value), and incrementing a character pointer makes it point to the nextcharstorage address (the address one byte beyond its current value).
在下面的示例程序中,我们演示如何用指针运算操作数组。首先声明类型与数组元素类型相匹配的指针变量:
In the following example program, we demonstrate how to use pointer arithmetic to manipulate an array. First declare pointer variables whose type matches the array’s element type:
1 | #define N 10 |
接着,把指针变量初始化为它们将要遍历的数组的基地址:
Next, initialize the pointer variables to the base address of the arrays over which they will iterate:
1 | // make the pointer point to the first element in the array |
然后,程序就可以通过指针解引用来访问数组的元素。这里我们先解引用,给数组元素赋值,再把指针变量加一,使它前进到指向下一个元素:
Then, using pointer dereferencing, our program can access the array’s elements. Here, we’re dereferencing to assign a value to an array element and then incrementing the pointer variable by one to advance it to point to the next element:
1 | // initialized letters and numbers arrays through pointer variables |
注意,在这个例子中,指针的值在循环内部递增。因此,递增指针的值就让它指向数组中的下一个元素。这种模式遍历数组每个元素的效果,与每次迭代访问 cptr[i] 或 iptr[i] 相同。
Note that in this example, the pointer values are incremented inside the loop. Thus, incrementing their value makes them point to the next element in the array. This pattern effectively walks through each element of an array in the same way that accessing
cptr[i]oriptr[i]at each iteration would.
原书注 · 指针运算的语义与底层的算术运算(The semantics of pointer arithmetic and the underlying arithmetic function)
指针运算的语义与类型无关:把任何类型的指针的值改变 N(ptr = ptr + N),都会让指针指向比当前值多 N 个存储位置的地方(即指向它当前所指元素之后第 N 个元素)。因此,递增任何类型的指针,都会使它指向其所指类型紧邻的下一个内存位置。
但是,编译器为指针运算表达式生成的实际算术运算,因指针变量的类型而异(取决于系统存储其所指类型所用的字节数)。例如,递增一个 char 指针会使它的值加一,因为紧邻的下一个有效 char 地址离当前位置 1 字节;递增一个 int 指针会使它的值加四,因为下一个有效整数地址离当前位置 4 字节。
程序员只需写 ptr++ 就能让指针指向下一个元素值。编译器会生成代码,按指针所指的对应类型加上相应的字节数。这次加法实际上把指针的值设为内存中该类型的下一个有效地址。
The semantics of pointer arithmetic are type independent: changing any type of pointer’s value by
N, (ptr = ptr + N) makes the pointer pointNstorage locations beyond its current value (or makes it point toNelements beyond the current element it points to). As a result, incrementing a pointer of any type makes it point to the very next memory location of the type it points to.However, the actual arithmetic function that the compiler generates for a pointer arithmetic expression varies depending on the type of the pointer variable (depending on the number of bytes the system uses to store the type to which it points). For example, incrementing a
charpointer will increase its value by one because the very next validcharaddress is one byte from the current location. Incrementing anintpointer will increase its value by four because the next valid integer address is four bytes from the current location.A programmer can simply write
ptr++to make a pointer point to the next element value. The compiler generates code to add the appropriate number of bytes for the corresponding type it points to. The addition effectively sets its value to the next valid address in memory of that type.
打印数组元素的值,就能看出上面的代码是如何修改它们的(我们先用数组下标、再用指针运算来访问每个数组元素的值):
You can see how the above code modified array elements by printing out their values (we show this first using array indexing and then using pointer arithmetic to access each array element’s value):
1 | printf("\n array values using indexing to access: \n"); |
输出如下:
Here’s what the output looks like:
1 | array values using indexing to access: |
指针运算可以用来遍历任何一块连续内存。下面是一个用指针运算初始化静态声明的二维数组的例子:
Pointer arithmetic can be used to iterate over any contiguous chunk of memory. Here’s an example using pointer arithmetic to initialize a statically declared 2D array:
译注
下面代码开头的注释与实际不符:由于 M 是 20,第 1 行的值是 20、21、22……39(见后面的输出),而不是注释里写的 100、110、120。注释大概沿用自早期版本的代码。
1 | // sets matrix to: |
输出如下:
The output will look like:
1 | 2D array values initialized using pointer arith: |
指针运算可以以任何模式访问连续的内存位置,可以从一块连续内存的任何地方开始、在任何地方结束。例如,把指针初始化为某个数组元素的地址之后,可以让它的值一次改变不止一个单位。例如:
Pointer arithmetic can access contiguous memory locations in any pattern, starting and ending anywhere in a contiguous chunk of memory. For example, after initializing a pointer to the address of an array element, its value can be changed by more than one. For example:
1 | iptr = &numbers[2]; |
执行上面的代码后,打印 numbers 数组的值会是这样(注意下标 2 和下标 6 处的值发生了变化):
After executing the preceding code, printing the
numbersarray’s values would look like this (note that the values at index 2 and index 6 have changed):
1 | numbers[0] = 0 |
指针运算也适用于动态分配的数组。不过,处理动态分配的多维数组时,程序员必须小心。例如,如果程序用多次 malloc 调用为二维数组逐行动态分配空间(方法 2,数组的数组),那么每一行都必须重新把指针设为指向该行起始元素的地址。之所以要重设指针,是因为只有同一行内的元素位于连续的内存地址上。另一方面,如果二维数组是用一次 malloc 分配「行数 × 列数」大小的空间(方法 1),那么所有行都在连续内存中(就像上例中静态声明的二维数组一样)。在后一种情况下,只需把指针初始化为指向基地址,之后用指针运算就能正确访问二维数组中的任何元素。
Pointer arithmetic works on dynamically allocated arrays too. However, programmers must be careful working with dynamically allocated multidimensional arrays. If, for example, a program uses multiple
malloccalls to dynamically allocate individual rows of a 2D array (method 2, array of arrays), then the pointer must be reset to point to the address of the starting element of every row. Resetting the pointer is necessary because only elements within a row are located in contiguous memory addresses. On the other hand, if the 2D array is allocated as a singlemallocof total rows times columns space (method 1), then all the rows are in contiguous memory (like in the statically declared 2D array from the example above). In the latter case, the pointer only needs to be initialized to point to the base address, and then pointer arithmetic will correctly access any element in the 2D array.