I have the following code which doesn't work. How can I fill in data into the memory block of UnsafeMutablePointer
? The bufferSize is 1024. I tried to fill 0, 1, 2...1023 into the buffer.
let pbuffer = UnsafeMutablePointer<UInt8>.alloc(bufferSize)
for index in 0...bufferSize - 1
{
pbuffer[index] = UInt8(index)
}
Thank you!
Your problem is not the UnsafeMutablePointer
, but rather that you're trying to initialize a UInt8
with a value that won't fit in it; UInt8
has a maximum value of 255
. So, up to a bufferSize
of 256
, your code will work fine; beyond that, it'll crash.
All you need to do to fix this is use a different type for your UnsafeMutablePointer
. If you want to go up to a bufferSize
of 1024
, a UInt16
will work fine (max value 65535
):
let bufferSize = 1024
let pbuffer = UnsafeMutablePointer<UInt16>.alloc(bufferSize)
for index in 0..<bufferSize
{
pbuffer[index] = UInt16(index)
}
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