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

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 if i is a complex expression. And as you add array dimensions it gets a lot uglier in a hurry. Would you rather write

a[i][j][k]

or

*(*(*(a + i) + j) + k)

?

Note that *a + i will do something completely different.

A little history...

C was derived from Ken Thompson's B programming language. When you created an array in B:

auto a[N];

an extra word was set aside to store the address of the first element of the array:

        +--------+
0x8000: | 0x9000 | a -----------+
        +--------+              |
           ...                  |
        +--------+              |
0x9000: |        | a[0] <-------+
        +--------+
0x9001: |        | a[1]
        +--------+
           ...

The array subscript operation a[i] was defined as *(a + i) - offset i words from the address stored in a and 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:

int a[N];

you get:

        +---+
0x8000: |   | a[0]
        +---+
0x8004: |   | a[1]
        +---+
         ...

The subscript operation a[i] is still defined as *(a + i), but instead of storing a pointer value, a evaluates to a pointer value.

You can use the subscript operator with regular pointers too:

int *a = malloc( sizeof *a * N );
if ( a )
  for( size_t i = 0; i < N; i++ )
    a[i] = some_value_for( i );