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

rempas rempas at tutanota.com
Mon Dec 5 06:24:52 UTC 2022


On Sunday, 4 December 2022 at 17:27:39 UTC, Nick Treleaven wrote:
> On Sunday, 4 December 2022 at 16:33:35 UTC, rempas wrote:
>
> (MemoryBlock.sizeof is 16 on my 64-bit system).
>
> The above adds 16 bytes to ptr.
>
> 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**."

Thanks! This explains it. And I have tried and I can only use "+" 
or "-" with a pointer so it explains it.

>
>> 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.

I think I get it! The first part about the arithmetic explains it 
all well. I was also able to fix my program. They way I see it, 
you return from a function by first casting the first operand and 
when you want to get a variable (or pass one to a function), you 
cast the whole expression. At least that's how it worked with my 
program.




More information about the Digitalmars-d-learn mailing list