Reputation: 24341
Since the structs
are value types in Swift, so their memory is ofcourse allocated on the stack.
My question is, why is the memory address not changed when different instances of struct
are assigned in the same variable.
Explanation:
For the below struct
,
struct Person {
var name: String
init(_ name: String) {
self.name = name
}
}
if I create the instances of Person
like,
var p = Person("John")
withUnsafePointer(to: &p) {
print("\(p) has address: \($0)") //0x000000010dcea3c0
}
p = Person("Jennifer")
withUnsafePointer(to: &p) {
print("\(p) has address: \($0)") //0x000000010dcea3c0
}
p = Person("Lisa")
withUnsafePointer(to: &p) {
print("\(p) has address: \($0)") //0x000000010dcea3c0
}
Why is the same address printed everytime?
Upvotes: 0
Views: 155
Reputation: 969
This is because you are using same variable. Take this example
var p (This is allocating memory to hold your value)
and now you are just changing the values and not the variable which is already been allocated to a memory location.
Upvotes: 4