I am seeing a very weird (or at least weird to me) behaviour regarding memory addresses when playing around with structs in Swift.
I have the following code in a Playground:
func address(o: UnsafeRawPointer) -> Int {
return Int(bitPattern: o)
}
struct Car {}
struct Garage {
let cars: [Car]
init() {
var cars = [Car]()
for _ in 0..<2 {
cars.append(Car())
}
print(NSString(format: "%p", address(o: &cars[0])))
self.cars = cars
}
}
_ = Garage()
_ = Garage()
The console prints the same memory address both times for the first element of the cars array, even though they are initialized in completely different Garage instances:
0x7fff2f1102e0
0x7fff2f1102e0
Could someone shed some light on what's happening here?
Thanks!
carswill give you unique addresses.cars[0]and pass that address to the function.cars.withUnsafeBufferPointer { bp in bp.baseAddress!.advanced(by: 0))), trying to replicate the semantics that&cars[0]would have in C (it would be a pointer expression equivalent to(cars + 0), i.e. a pointer into the buffer), yet I still get the same address both times. Why could that be?