/*用下标和指针操作数组*/
#include <stdio.h>
main()
{
int i, offset, b[] = {10, 20, 30, 40};
int *ptr = b;
printf("Array b printed with array subscript notation: \n");
for(i=0; i<=3; i++)
printf("b[%d] = %d \n", i, b[i]);
printf("\nPointer/offset notation where the pointer is the array name: \n");
for(offset=0; offset<=3; offset++)
printf("*(b+%d) = %d \n", offset, *(b+offset));
printf("\nPointer subscript notation: \n");
for(i=0; i<=3; i++) /* 指针/下标表示法:像数组一样带下标的指针 */
printf("ptr[%d] = %d \n", i, ptr[i]);
printf("\nPointer/offset notation: \n");
for(offset=0; offset<=3; offset++) /* 指针/偏移量表示法 */
printf("*(ptr+%d) = %d \n", offset, *(ptr+offset));
return 0;
}
#include <stdio.h>
main()
{
int i, offset, b[] = {10, 20, 30, 40};
int *ptr = b;
printf("Array b printed with array subscript notation: \n");
for(i=0; i<=3; i++)
printf("b[%d] = %d \n", i, b[i]);
printf("\nPointer/offset notation where the pointer is the array name: \n");
for(offset=0; offset<=3; offset++)
printf("*(b+%d) = %d \n", offset, *(b+offset));
printf("\nPointer subscript notation: \n");
for(i=0; i<=3; i++) /* 指针/下标表示法:像数组一样带下标的指针 */
printf("ptr[%d] = %d \n", i, ptr[i]);
printf("\nPointer/offset notation: \n");
for(offset=0; offset<=3; offset++) /* 指针/偏移量表示法 */
printf("*(ptr+%d) = %d \n", offset, *(ptr+offset));
return 0;
}
以上代码在VC环境下运行。
输出:
Array b printed with array subscript notation:
b[0] = 10
b[1] = 20
b[2] = 30
b[3] = 40
Pointer/offset notation where the pointer is the array name:
*(b+0) = 10
*(b+1) = 20
*(b+2) = 30
*(b+3) = 40
Pointer subscript notation:
ptr[0] = 10
ptr[1] = 20
ptr[2] = 30
ptr[3] = 40
Pointer/offset notation:
*(ptr+0) = 10
*(ptr+1) = 20
*(ptr+2) = 30
*(ptr+3) = 40
注解:
1. 数组名是一个常量指针。因此,对上例来说b+=3;是不对的。
2. C语言中的指针和数组有着密切的关系,它们几乎可以互换。
3. 数组名可认为是一个常量指针,指针可用来完成涉及数组下标的操作。
4. 因为数组下标在编译的时候要被转换成指针表示法,所以用指针编写数组下标表达式可节省编译时间。然而在操作数组时最好用下标表示而不使用指针表示法,程序可能会更清晰。

浙公网安备 33010602011771号