Pointer addition and element size

后端 未结 3 1267
无人共我
无人共我 2020-12-16 17:07

At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

Under: Pointer addition and element size

There is the following co

相关标签:
3条回答
  • 2020-12-16 17:35

    The comment in the code you post it explains it: addition of an integer x to a pointer increases the pointer's value by x multiplied by the sizeof the type it is pointing to.

    This is convenient because it doesn't usually make sense to change the pointer in smaller increments - you wouldn't want it to point into the middle of one of the elements.

    0 讨论(0)
  • 2020-12-16 17:52

    (I assume that you mean "1" in the last line, not "p")

    Pointer arithmetic in both C and C++ is a logical addition, not a numeric addition. Adding one to a pointer means "produce a pointer to the object that comes in memory right after this one," which means that the compiler automatically scales up whatever you're incrementing the pointer with by the size of the object being pointed at. This prevents you from having a pointer into the middle of an object, or a misaligned pointer, or both.

    0 讨论(0)
  • 2020-12-16 17:55

    because p is pointer to a type with size 4 bytes. + operator on pointers is actually pointer shift. compiler knows the size of pointed type and shifts it by appropriate value

    if you change int to short, p will be shifted by 2 bytes

    0 讨论(0)
提交回复
热议问题