var b: array[5, int]
type
ArrRef = ref array[5, int]
var c : ArrRef
echo repr(c) # nil
c = addr b # doesn't compile, says type is Array constructor, expected reference
In Nim, how can I pass references to arrays instead of passing by value? See the above code for what I have so far.
An array of references is illegal because a reference is not an object. According to the C++ standard, an object is a region of storage, and it is not specified if a reference needs storage (Standard §11.3. 2/4). Thus, sizeof does not return the size of a reference, but the size of the referred object.
After a successful compilation, we can run our program. On Linux we can run our program by typing ./helloworld in the terminal, and on Windows we do it by typing helloworld.exe . c is telling Nim to compile the file, and -r is telling it to run it immediately.
In Nim ref
s are on the heap and have to be allocated with new
. You can't just use a stack array as a ref
because that would be unsafe: When the array disappears from the stack, the ref
points to some wrong memory. Instead you have two choices: You can use unsafe ptr
s instead. Other than ref
s, they are not garbage collected and can be used for unsafe stuff. Alternatively you can make b
a ref array
directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With