const pointer and array

const pointer starting from basic.

1.int  var;                                      //we get a int variable named var

2.const  int  var;                          //we get a int variable named var and it is read-only(const)

3.int  *p;                                       //from 1, we get a int variable *p(because * is the dereferencing operator, thus p is pointer)

4.const  int  *p;                           //from 2,we get a int variable *p and it is read-only

5.int  *const  p;                           //from 3,we get a int variable *const  p, and p is read-only, this can be read as "int   *(const  p)"

6.const  int  *const  p                //from 4 and 5, we get a int variable *const  p and it is read-only, p is also read-only. this can be read as "const  int  *(const  p)"


      array in C is actually compiled as pointer. if we define a array like int ar[n], then we can get its elements value by dereferencing it as a pointer *(ar + i).

but is array really a pointer? yes and no.

      when defining an array : int  ar[n], we actually define it like 5------int  *const  ar.      when we defining a const arr : const  ar[n], we define it like 6------const  int  *const  ar

they are just the same!

      when passed as parameter to a function, they act just the same. neither can you redirect it, nor change the value it points to. you can not even change the value it not point to  by using it. suppose :

void foo(const int ar[]) {
    ar[i]++;                 //error
}

and

const int *const p;
(*(p  + 1))++;               //error too
however, you can change the value by using an other pointer

int *q = p;
(*(p + 1))++;                  //this is fine, you just get a warning 

what an array can provide and a pointer can't is the size information : sizeof ar, but when passed to function, this information lost





 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值