I fail to see what the "all" should be? If I add 4 random memory addresses I 
just get a meaningless value. But thats probably the error you talk about.

You need to add the size of the type the `pointer` points at. Thats the reason 
you can't create an "+" like function without more information. Adding the size 
of the pointer type only will work for pointers to pointers and types which 
happen to have the same size as the pointer type.

But you have a type like `var a: ptr int16` and for this you can find the size 
of the elements with a[].sizeof. Therefor you can create the plus and minus 
functions for them.
    
    
    var a: ptr int16
    
    var t = @[1.int16, 2.int16, 3.int16]
    
    proc `+`[T](a: ptr T, b: int): ptr T =
        if b >= 0:
            cast[ptr T](cast[uint](a) + cast[uint](b * a[].sizeof))
        else:
            cast[ptr T](cast[uint](a) - cast[uint](-1 * b * a[].sizeof))
    
    template `-`[T](a: ptr T, b: int): ptr T = `+`(a, -b)
    
    a = t[0].addr
    echo a[]
    a = a + 1
    echo a[]
    a = a + 1
    echo a[]
    a = a + -1
    echo a[]
    a = a - 1
    echo a[]
    

[Run It](https://glot.io/snippets/ej532ijerl)

There may be more elegant solutions for that code. This was the first example 
which I had in mind. And there are unchecked arrays too.

Reply via email to