Cprogramming 简明教程
Pointer to an Array in C
数组名是数组第一个元素的常量指针。因此,在此声明中,
An array name is a constant pointer to the first element of the array. Therefore, in this declaration,
int balance[5];
balance 是指向 &balance[0] 的指针,即数组第一个元素的地址。
balance is a pointer to &balance[0], which is the address of the first element of the array.
Example
在此代码中,我们拥有一个指针 ptr ,它指向名为 balance 的整数数组第一个元素的地址。
In this code, we have a pointer ptr that points to the address of the first element of an integer array called balance.
#include <stdio.h>
int main(){
int *ptr;
int balance[5] = {1, 2, 3, 4, 5};
ptr = balance;
printf("Pointer 'ptr' points to the address: %d", ptr);
printf("\nAddress of the first element: %d", balance);
printf("\nAddress of the first element: %d", &balance[0]);
return 0;
}
Output
在这三个情况下,您获得相同的输出 −
In all the three cases, you get the same output −
Pointer 'ptr' points to the address: 647772240
Address of the first element: 647772240
Address of the first element: 647772240
如果您获取指针 ptr 指向的地址处存储的值(即 *ptr ),它将返回 1 。
If you fetch the value stored at the address that ptr points to, that is *ptr, then it will return 1.
Array Names as Constant Pointers
将数组名用作常量指针,反之亦然,这是合法的。因此, *(balance + 4) 是访问 balance[4] 处数据的合法方式。
It is legal to use array names as constant pointers and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].
一旦您在“ ptr ”中存储第一个元素的地址,您便可以使用 ptr 、 (ptr + 1) 、 *(ptr + 2) 等来访问数组元素。
Once you store the address of the first element in "ptr", you can access the array elements using ptr, (ptr + 1), *(ptr + 2), and so on.
Example
以下示例演示以上讨论的所有概念 −
The following example demonstrates all the concepts discussed above −
#include <stdio.h>
int main(){
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *ptr;
int i;
ptr = balance;
/* output each array element's value */
printf("Array values using pointer: \n");
for(i = 0; i < 5; i++){
printf("*(ptr + %d): %f\n", i, *(ptr + i));
}
printf("\nArray values using balance as address:\n");
for(i = 0; i < 5; i++){
printf("*(balance + %d): %f\n", i, *(balance + i));
}
return 0;
}
当你运行这段代码时,它将产生以下输出:
When you run this code, it will produce the following output −
Array values using pointer:
*(ptr + 0): 1000.000000
*(ptr + 1): 2.000000
*(ptr + 2): 3.400000
*(ptr + 3): 17.000000
*(ptr + 4): 50.000000
Array values using balance as address:
*(balance + 0): 1000.000000
*(balance + 1): 2.000000
*(balance + 2): 3.400000
*(balance + 3): 17.000000
*(balance + 4): 50.000000
在上面的示例中, ptr 是一个指针,可以存储 double 类型的变量地址。一旦我们获得 ptr 中的地址, *ptr 便会给我们存储在 ptr 中的地址中可用的值。
In the above example, ptr is a pointer that can store the address of a variable of double type. Once we have the address in ptr, *ptr will give us the value available at the address stored in ptr.