The purpose of arrays in C, when pointers could have done the job

cpointers

Arrays and pointers are not the same thing in C, although they are related and can be used similarly. So far we all agree.

However, I don't see why arrays were included in C, when pointers could have done their job perfectly.

I am not saying to remove the array notation (e.g, a[5] or int a[4] = {0,1,2,3};), which is quite useful and convenient. But you could have that same notation working on top of pointers (as is the case), as a cosmetic measure. So the array notation is not a reason to have arrays, just the notation!

The only difference I see is that arrays are constant pointers, and the size of memory they point to can't be changed. But this can be achieved with pointers as well, exactly by making them constant (the memory wouldn't be of fixed size, but I am not sure if this is an issue).

So why not have only pointers and let the programmer decide how the pointer should behave (i.e., constant, not constant, fixed size, variable size, etc)?

Best Answer

Arrays are contiguous memory created on the stack. You can't guarantee contiguous stack memory without this syntactic sugar, and even if you could, you'd have to allocate a separate pointer in order to be able to do the pointer arithmetic (unless you wanted to do *(&foo + x), which I'm not sure but it might violate l-value semantics, but is at least quite awkward, and would scream out for some kind of syntactic sugar). Design-wise, it also is a form of encapsulation, since you can refer to the collection with a single identifier (which would otherwise require a separate pointer). And even if you could allocate them contiguously and allocated a separate pointer to reference them, you'd have either int fooForSomething, fooForSomethingElse... which forces a fair amount of creativity as your collection grows, so you might think to simplify with int foo1, foo2 ..., which looks just like an array but is harder to maintain.