C 语言中指向数组的指针
数组名是指向数组首元素的常量指针。因此,在此声明中:
int balance[5];
balance 是一个指向 &balance[0] 的指针,而 &balance[0] 是数组首元素的地址。
示例
在此代码中,我们有一个指针 ptr,它指向名为 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("
Address of the first element: %d", balance);
printf("
Address of the first element: %d", &balance[0]);
return 0;
}
输出
在这三种情况下,您将获得相同的输出 -
Pointer 'ptr' points to the address: 647772240 Address of the first element: 647772240 Address of the first element: 647772240
如果获取 ptr 指向的地址(即 *ptr)中存储的值,则返回 1。
数组名称作为常量指针
将数组名称用作常量指针是合法的,反之亦然。因此,*(balance + 4) 是访问 balance[4] 处数据的合法方式。
将第一个元素的地址存储在"ptr"中后,您可以使用 *ptr、*(ptr + 1)、*(ptr + 2) 等访问数组元素。
示例
以下示例演示了上面讨论的所有概念 -
#include <stdio.h>
int main(){
/* 一个包含 5 个元素的数组 */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *ptr;
int i;
ptr = balance;
/* 输出每个数组元素的值 */
printf("Array values using pointer:
");
for(i = 0; i < 5; i++){
printf("*(ptr + %d): %f
", i, *(ptr + i));
}
printf("
Array values using balance as address:
");
for(i = 0; i < 5; i++){
printf("*(balance + %d): %f
", i, *(balance + i));
}
return 0;
}
输出
运行此代码时,将产生以下输出 -
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 中存储的地址处的值。

