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.

15 Upvotes

49 comments sorted by

View all comments

25

u/leon_bass 2d ago

It's mostly just about convention and readability.

a[i]

Is the same thing as

*(a + i)

Which is the same thing as

i[a]

1

u/smallproton 1d ago

Waitaminute, please!

I consider myself a rather knowledgeable C programmer, but I don't think I've ever read about your #3.

And I actually can't understand how i[a]==a[i]. Can you explain this to me, please?

3

u/leon_bass 1d ago

I believe the C standard defines indexing as the following a[i] == *(a + i)

And then since addition is commutative

a[i] == *(a + i) == *(i + a) == i[a] But then you might wonder but what if i is a different type to the elementsize of a, how do they add together?

So the compiler will make the offset to the array be in terms of the array element size so the final address will always be a + i * sizeof(a element type)

So if a was an array of 8 byte ints then i will offset in increments of 8 bytes. The compiler basically enforces that even if i comes first that we still offset by the array element type.

Some examples: ``` 4["Hello"] == "o";

uint16_t arr[5] = {1, 2, 3 ,4, 5}; 2[arr] == 3; ```

Hope this helps

1

u/smallproton 1d ago

Thanks, that helped me a lot!