How ptr arithmitic works??? It doesn't make any sense....

Nick Treleaven nick at geany.org
Sun Dec 4 17:27:39 UTC 2022


On Sunday, 4 December 2022 at 16:33:35 UTC, rempas wrote:
> struct MemoryBlock {
>   char* ptr;
>   ulong length;
> }

(MemoryBlock.sizeof is 16 on my 64-bit system).

> void* ptr = cast(void*)0x7a7;
>
> void* right() {
>   return cast(MemoryBlock*)(ptr + MemoryBlock.sizeof); // Cast 
> the whole expression between paranthesis. Got the right value!
> }

The above adds 16 bytes to ptr.

> void* wrong() {
>   return cast(MemoryBlock*)ptr + MemoryBlock.sizeof; // First 
> cast the `ptr` variable and then add the number. Got a wronge 
> value...
> }

The above adds 16 * MemoryBlock.sizeof bytes (16 * 16) to ptr, 
because ptr is cast first. Should be `+ 1` to be equivalent.

https://dlang.org/spec/expression.html#pointer_arithmetic

"the resulting value is the pointer plus (or minus) the second 
operand **multiplied by the size of the type pointed to by the 
first operand**."

> char* return_address_wrong() {
>   MemoryBlock* local_ptr = cast(MemoryBlock*)ptr;
>   return cast(char*)(local_ptr + MemoryBlock.sizeof); // Casted 
> the whole expression. BUT GOT THE WRONG VALUE!!!! Why???
> }

Because you are adding to a pointer that points to a 16-byte 
block, rather than a void* which points to a single byte.

> char* return_address_right() {
>   MemoryBlock* local_ptr = cast(MemoryBlock*)ptr;
>   return cast(char*)local_ptr + MemoryBlock.sizeof; // Now I 
> first casted the `local_ptr` variable and then added the number 
> but this time this gave me the right value....
> }

The casted pointer points to a single byte.


More information about the Digitalmars-d-learn mailing list