Pointer arithmetics in C++ uses sizeof(type) incremention instead of byte incremention?

前端 未结 3 657
南笙
南笙 2021-01-24 07:20

I am confused by the behavior of pointer arithmetics in C++. I have an array and I want to go N elements forward from the current one. Since in C++ pointer is memory address in

3条回答
  •  无人共我
    2021-01-24 07:39

    Your error in reasoning is right here: "Since in C++ pointer is memory address in BYTES, [...]".

    A C/C++ pointer is not a memory address in bytes. Sure, it is represented by a memory address, but you have to differentiate between a pointer type and its representation. The operation "+" is defined for a type, not for its representation. Therefore, when it is called one the type int *, it respects the semantics of this type. Therefore, + 1 on an int * type will advance the pointer as much bytes as the underlying int type representation uses.

    You can of course cast your pointer like this: (int)myPointer. Now you have a numeric type (instead of a pointer type), where + 1 will work as you would expect from a numeric type. Note that after this cast, the representation stays the same, but the type changes.

提交回复
热议问题