Tuesday, May 3, 2011

How can I print out the Memory Adress of an variable?

I'd like to print what's behind an &myVariable. I tried NSLog(&myIntVar); but it won't work.

From stackoverflow
  • The argument to NSLog needs to be an NSString, so you want

    NSLog(@"%p", &myIntVar);
    
    smorgan : Good point! I've updated the answer accordingly :)
  • Try:

    NSLog(@"%p", &myIntVar);
    

    or

    NSLog(@"%lx", (long)&myIntVar);
    

    The first version uses the pointer-specific print format, which assumes that the passed parameter is a pointer, but internally treats it as a long.

    The second version takes the address, then casts it to a long integer. This is necessary for portability on 64-bit platforms, because without the "l" format qualifier it would assume that the supplied value is an integer, typically only 32-bits long.

    Alnitak : Apple specifically mention the latter method themselves: http://developer.apple.com/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1

0 comments:

Post a Comment