user1101733
user1101733

Reputation: 258

Pointer and malloc in Swift

I am trying to convert this into swift.

Facing issue at memory allocation logic

Byte *p[10000];

p[allocatedMB] = malloc(1048576);
memset(p[allocatedMB], 0, 1048576);

How to write this in swift?

Upvotes: 2

Views: 4460

Answers (1)

Martin R
Martin R

Reputation: 540005

You can use malloc from Swift, it returns a "raw pointer":

var p: [UnsafeMutableRawPointer?] = Array(repeating: nil, count: 10000)
var allocatedMB = 0

p[allocatedMB] = malloc(1048576)
memset(p[allocatedMB], 0, 1048576)

Alternatively, use UnsafeMutablePointer and its allocate and initialize methods:

var p: [UnsafeMutablePointer<UInt8>?] = Array(repeating: nil, count: 10000)
var allocatedMB = 0

p[allocatedMB] = UnsafeMutablePointer.allocate(capacity: 1048576)
p[allocatedMB]?.initialize(to: 0, count: 1048576)

Upvotes: 6

Related Questions