Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a single pointer act like an array and the dereference operator (*) isn´t needed to access the pointed element?

int *insertZeroPosition(int *pf,int n,int k){
    int *ptr=(int *)calloc(n+1,sizeof(int));
    int i;
    ptr[0]=k;
    for (i=1;i<n+1;i++,pf++){
        ptr[i]=*pf; 
    }
    return ptr;
}

Why is it ptr[i]=*pf instead of *ptr[i]=*pf even though ptr is a pointer?

like image 468
Rizwan Mohamed Kareem Avatar asked Nov 24 '25 23:11

Rizwan Mohamed Kareem


1 Answers

The syntax p[i] is equivalent to *((p) + (i)). The dereference is still there, even with the array-subscript syntax.

C Standard, § 6.5.2.1.2:

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).

You can rewrite the code to say *(ptr + i) = *pf if you want; there's no difference.

like image 180
Govind Parmar Avatar answered Nov 27 '25 21:11

Govind Parmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!