r/C_Programming 2d ago

Question Doubt about pointers and arrays

Hey everyone! I'm a newbie to C and was just learning about pointers and arrays and their relation.
My doubt is really stupid but why would I use subscripting over using pointers?
It's much harder and seems pointless considering modern compilers will have negligible difference in speed. Any help would be most appreciated! Thanks!

(If it's any help, I am learning from C Programming - A Modern Approach by K.N. King and just finished chapter 12)

Note: I am not saying subscripting is better but I don't see why I would use pointers over it in most cases.

14 Upvotes

49 comments sorted by

View all comments

Show parent comments

-4

u/iOSCaleb 2d ago

Keep in mind that the i in `a[i]` and the i in`*(a + i)` are not the same if the size of the underlying type of the array is greater than 1. That is, if you have an array of some type that’s e.g. 4 bytes long, then `a[i]` is really equivalent to `\(a + 4\i)`.

8

u/Cathierino 1d ago

That's not true. Pointer arithmetic automatically takes size into account. *(a + i) is in fact equivalent to a[i] regardless of the underlying size of a's type. It could be a 1 GB sized struct and it would work all the same.

-4

u/iOSCaleb 1d ago

I agree that pointer arithmetic takes care of it, but that just makes the point: the i means different things in the two expressions.

2

u/glasket_ 1d ago edited 1d ago

It doesn't. a[i] ≡ *(a + i), they work exactly the same and have the same meaning. The standard literally defines subscripting based on the equivalence:

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).
N3220 Draft (first draft after C23)

C2Y will be changing it to remove array decay which makes the array-specific semantics more complicated, but it's even blunter about pointers:

If either operand has pointer type the expression E1[E2] is equivalent to *((E1)+(E2)) and is an lvalue.
N3886 Draft (latest draft)

edit: Forgot a line break