3
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?

12
  • What is a pointerunction? Commented Dec 5, 2019 at 17:39
  • 2
    ptr[x] is equivalent to *(ptr+x). This is really a basic syntax question. Commented Dec 5, 2019 at 17:40
  • Does this answer your question? What is the difference between char s[] and char *s? Commented Dec 5, 2019 at 17:41
  • 2
    Because ptr[i] is exactly the same as *(ptr+i), you can also say i[ptr] and kind of freak people out :-) Commented Dec 5, 2019 at 17:54
  • 2
    @RobertS-ReinstateMonica they are the same because the language says so. Arrays are not first-class data types in C - though they are in other languages - and I'm not sure how to explain it more than that. C defined array access notation in terms of derference-pointer plus index. Now it's true that ptr[i] and (ptr + i) are not the same thing - the first accesses the element at the array, while the second only computes the address, but adding the deference *(ptr + i) accesses the element. Commented Dec 5, 2019 at 18:00

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.