5 ms·
pointers ARE ints if pointers are not integers how can you iterate through an arbitrary array using char* ?
by enriquto 8y ago
pointers ARE ints
if pointers are not integers how can you iterate through an arbitrary array using char* ?
- jcranmer 8y agoPointers are integers on most hardware, if you ignore the complexities of multiple address spaces (i.e., a feature present on virtually anything that's not a general-purpose CPU) or segmentation (i.e., the most common CPU architecture for desktop and server processors). In C, however, pointers are not integers. I've not fully built any kind of operational semantics for C, so I can't say what the full list of features you need to track for pointers is for sure, but I can take a stab at how you could describe it. A pointer consists of a tag of the object being stored in the object model (which needs to tell you what the current dynamic type of the object is and its size and alignment in addition to the actual memory contents of the object) as well as an offset of where it points inside that object. Iterating through an array would merely be incrementing (or decrementing, as the case may be) the offset field of the pointer, subject of course to the well-definedness characteristics that you can't exceed one past the end of the object or go before the beginning of the object.
- yourbandsucks 8y agoThat's... not really how it is. At compile time, the compiler knows the type of a pointer, so it can interpret struct_ptr->field and do the proper arithmetic (field is 20 bytes offset into struct). But when running, the pointers are just int64s on the stack. Check stdint.h. It's all right there. Anyone writing C 'gets' roughly what's happening and knows the shape of their structs in memory.