How do I write a for loop to iterate over an array of floats, given the intPtr for the start of the array?
It's C# in Unity, so I know the bytes of a float are 4. But am having only crashes when trying to increment from the intPtr by the simple use of the number 4 as a value to increment by.
This is what's not working:
float myFloatVar = 42.42f
for ( int i = varIntPtr ; i < varIntPtr + 12 ; i+=4 ) {
presumedToBeAnArrayLocation[i] = myFloatVar * i;
}
If you have a pointer to the start of an array, then unless that array is externally pinned: your code is already irretrievably broken - an unmanaged pointer doesn't get updated with GC movement, so you now have undefined behaviour.
If we assume that it is pinned, or is unmanaged memory (and therefore not subject to GC movement), then something like:
However, it is usually preferable to use spans when possible: