Swift: populating data in unsafeMutablePointer like UInt8 does not work

I have the following code that does not work. How can I fill data in a UnsafeMutablePointer memory UnsafeMutablePointer ? BuffSize is 1024. I tried to fill 0, 1, 2 ... 1023 in the buffer.

 let pbuffer = UnsafeMutablePointer<UInt8>.alloc(bufferSize) for index in 0...bufferSize - 1 { pbuffer[index] = UInt8(index) } 

Thanks!

+7
swift
source share
1 answer

Your problem is not UnsafeMutablePointer , but that you are trying to initialize UInt8 with a value that does not fit in it; UInt8 has a maximum value of 255 . So, until bufferSize 256 , your code will work fine; in addition, it will crash.

All you need to do to fix this is using your UnsafeMutablePointer type for another type. If you want to go to bufferSize 1024 , a UInt16 will work fine (maximum value 65535 ):

 let bufferSize = 1024 let pbuffer = UnsafeMutablePointer<UInt16>.alloc(bufferSize) for index in 0..<bufferSize { pbuffer[index] = UInt16(index) } 
+8
source share

All Articles