指针和数组的互换性[c][code]

/* 用下标和指针操作数组 */
#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. 因为数组下标在编译的时候要被转换成指针表示法,所以用指针编写数组下标表达式可节省编译时间。然而在操作数组时最好用下标表示而不使用指针表示法,程序可能会更清晰。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值