In attempt to explain that arrays are just pointers (in C++) to our class, my professor showed us this:
array[5] // cout'ing this
*(array + 5) // would return the same value as this
I’m having a little trouble completely understanding it. Here’s my thinking:
array is the address of the first location and so if we add 5 to that address, we move 5 addresses in memory. The pointer operator pulls the data from the memory location.
Is this the correct idea? The idea still feels foggy with me and just feel like I don’t understand it completely. I think hearing someone else explain it might help me understand it more. Thanks in advance!
You’ve got the right idea.
Arrays implicitly cast to pointers. Interestingly,
[]works on pointers, not arrays.a
[b]Subscript operator is defined as*(a + (b)).[]is used as syntactic sugar – it’s much more pleasant to writearray[5]instead of*(array + 5)Pointer arithmetic with a pointer and an integer
p + iincreases the address atpbyi * sizeof(*p)bytes.The
*operator performs indirection. It will give you what the pointer is pointing to.