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

前端 未结 3 656
南笙
南笙 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.

    0 讨论(0)
  • 2021-01-24 07:46

    A "pointer" points to a location.

    When you "increment", you want to go to the next, adjacent location.

    Q: "Next" and "adjacent" depend on the size of the object you're pointing to, don't they?

    Q: When you don't use "sizeof()", everything works, correct? Why? What do you think the compiler is doing for you, "behind your back"?

    Q: What do you think should happen if you add your own "sizeof()"?

    ON TOP OF the "everything works" scenario?

    0 讨论(0)
  • 2021-01-24 07:56

    pointers point to addresses, so incrementing the pointer p by N will point to the Nth block of memory from p.

    Now, if you were using addresses instead of pointers to addresses, then it would be appropriate to add N*sizeof(type).

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