Lesson Idea: Arrays, Pointers, and Syntactic Sugar One of the most challenging concepts to instill in new CS students is 0-indexing (indeed, the pedagogy of this fact probably merits its own discussion). Another difficult topic -- although a slightly more advanced one -- is pointers. (I'm thinking particularly of programming in C.) With this question I'm wondering if part of the difficulty is the syntactic sugar in C that allows the following to be equivalent:

// declare array of 5 ints on the stack
int num[5];

// use array notation to change first element
num[0] = 42;

// use pointer arithmetic to change first element
*(num + 0) = 42;


With array notation, we are explicit with 0-indexing, but the logic of it isn't apparent. Yet, with pointer arithmetic, it's more clear (I think...) why we use 0: the pointer stores the base address, so dereferencing the pointer brings us to that address which is where the array logically begins.

Comfort with this leads to the topic of memory management on the heap with something like this:

// declare array of 5 ints on the heap
int *num = malloc(sizeof(int) * 5);

// use pointer arithmetic to change first element
*num = 42;


I am toying with expanding my introduction on arrays next year to include this particular use of pointers. I recognize that it would involve taking maybe a single lesson on arrays and expanding to something closer to a week long to tie together all these ideas.

However, is it worth putting aside the syntactic sugar in order to understand more accurately the indexing of arrays? On the other hand, does the introduction of pointers and memory complicate the process so much so that confusion about arrays will increase rather than decrease? (I'm thinking of this is a "lesson idea feedback" discussion.)
This is a great explanation of why 0-indexing exists. As someone who barely knows what a pointer is, your explanation made perfect sense. If you wanted to dumb it down a little you could phrase it as:


  When you create an array, the variable you assign that array to is actually a pointer to the first element. Lets create an array num. When you want to modify the array, to get a pointer to the first element you want to add 0 to num, because num points to the first element. For the second element, you add 1 to num because num is a pointer to the first element and the second is one after the first. Then for the third element, you add 2 to `num, and so on, so that the first is adding 0, the second is adding 1, and the third is adding 2.


A useful resource is this website which explains how num[i] is syntactic sugar for pointer arithmetic (*(num+i)).

I think that this discussion will increase clarity and be very useful because it makes sense as a logical way to implement arrays and revels a cool thing about the language. I'm not sure that you have to talk about memory, but talking about pointers is certainly worthwhile for this example.