How do I make a pointer to the first element in an array in Red/System?
Assigning an address to a pointer is no problem:
my-integer: 1
ptr: declare pointer! [integer!]
ptr: :my-integer
The array is declared.
buffer: as int-ptr! allocate 1009 * size? integer!
but.
ptr: :buffer
is not the way, nor is.
ptr: ::buffer
ptr: :buffer/1
ptr: :(buffer/1)
Anyone knows how to do this?
Regards,
Arnold
Pointers to an array points the address of memory block of an array variable. The following is the syntax of array pointers. datatype *variable_name[size]; Here, datatype − The datatype of variable like int, char, float etc.
p = arr; // Points to the whole array arr. p: is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole array arr. The base type of p is int while base type of ptr is 'an array of 5 integers'.
Access Array Elements Using Pointers data[0] is equivalent to *data and &data[0] is equivalent to data. data[1] is equivalent to *(data + 1) and &data[1] is equivalent to data + 1. data[2] is equivalent to *(data + 2) and &data[2] is equivalent to data + 2.
How is the 3rd element in an array accessed based on pointer notation? a[3] in C is equivalent to *(a + 3) in pointer notation.
As both ptr and buffer are pointers to integer data, you simply assign one to the other:
ptr: buffer
The :variable
syntax is only required to get the address of what would be called "primitive" types in Java. That equates to byte!, integer!, float!, float32! and logic! in the current version of Red/System. Without the leading :
, the compiler will provide the value stored in the variable.
All other types such as c-string! and struct! (and hence alias!) are in fact pointers. So the compiler provides their value when they are referenced, which is a memory address.
When you reference a word, the Red/System compiler provides the value stored in it:
print i ;; will print the value stored in i
When you use a set-word (a variable with a :
appended to the name), the compiler stores a value in it:
i: 1 ;; stores 1 in variable i
When you use a get-word (a variable with a :
inserted at the beginning of the name), the compiler provides the address of the variable.
int-ptr: :i ;; stores the address of i in int-ptr
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