Frage

I'm using objc_[sg]etAssociatedObject(), and this function uses a memory address as a key. If I pass the same string literal - e.g. "UIImageForTexture" - into the function from two different files, will the two string literals have:

  1. the same memory address?
  2. different memory addresses?
  3. it depends on some other factors.
  4. it's undefined.

I can do this more explicitly by sticking the literal in a file somewhere and referring to it via an extern but I'd like to know if I can avoid having to do that.

War es hilfreich?

Lösung

This is going to be an implementation defined behavior from the C99 draft standard section 6.4.5 String literals paragraph 6 says:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

Andere Tipps

It's whether two string literals with same content (e.g. char *p1="abc; char *p2="abc";) have the same address or different address is an implementation detail. p1 and p2 may be equal or may not be equal. C standard guarantees neither of them.

So the answer is (3) It depends on the implementation/optimization.

Instead of passing string literals directly, you can use pointers to them and pass them instead. That way, you can reliably handle them and not worry about (1) and (2).

This may be of interest: Addresses of two pointers are same?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top