I have already asked that question on StackOverflow forum, but it seems that most Crystal programmers are here. I am just trying to understand how to work with pointers in Crystal, I know they are “not safe”, and I don’t need that explanation since I have a C programming background.
So the example is gonna be the same, I need to point the element
[x][y] of the array (which is of type
Room). I have modified my code according to the information provided by Johannes Müller. Now my method for getting the address of an element looks like:
def map_ptr(x : Int32, y : Int32) p = @map.to_unsafe[x].to_unsafe + y pointerof(p) end
The type it gives me is a
Pointer(Pointer(Room), which seems odd. The fact that I point to a local variable seems also wrong, but if I do not pass it as a variable I get the error:
Error: can't take address of @map.to_unsafe[x].to_unsafe + y
However, I can not dereference the above pointer correctly. When I type:
current_room = map_ptr(0, 0) current_room.value.value.my_method
then error says:
Error: undefined method 'value' for Room (compile-time type is (Pointer(Room) | Room))
current_room.value.my_method is also wrong as it gives me:
Error: undefined method 'my_method' for Pointer(Room)
This seems like a never ending loop, what did I wrong?