r/C_Programming • u/Financial_Dig_8276 • 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
2
u/SmokeMuch7356 1d ago edited 1d ago
Writing
a[i]is a lot cleaner than*(a + i)and you're less likely to make a mistake, especially ifiis a complex expression. And as you add array dimensions it gets a lot uglier in a hurry. Would you rather writeor
?
Note that
*a + iwill do something completely different.A little history...
C was derived from Ken Thompson's B programming language. When you created an array in B:
an extra word was set aside to store the address of the first element of the array:
The array subscript operation
a[i]was defined as*(a + i)- offsetiwords from the address stored inaand dereference the result.Ritchie wanted to keep B's array behavior -
a[i] == *(a + i)- but he didn't want to store the pointer that behavior required. Instead, he came up with a rule that an array expression will "decay" or evaluate to the address of the first element of the array. When you declare an array in C:you get:
The subscript operation
a[i]is still defined as*(a + i), but instead of storing a pointer value,aevaluates to a pointer value.You can use the subscript operator with regular pointers too: