Skip to content

Instantly share code, notes, and snippets.

@strager
Last active August 29, 2015 14:16
Show Gist options
  • Save strager/c15581719d7cad8ffe7a to your computer and use it in GitHub Desktop.
Save strager/c15581719d7cad8ffe7a to your computer and use it in GitHub Desktop.
#include <stdio.h>
int
main(int argc, char **argv) {
int x = 1;
int y = 2;
int *xp = &x;
int *yp = &y;
printf("1: xp = %p; *xp = %d\n", xp, *xp);
printf("2: yp = %p; *xp = %d\n", yp, *yp);
int *zp = NULL;
int **pp = &zp;
printf("3: pp = %p; *pp = %p; zp = %p\n", pp, *pp, zp);
*pp = xp;
printf("4: pp = %p; *pp = %p; **pp = %d; zp = %p\n", pp, *pp, **pp, zp);
*pp = yp;
printf("5: pp = %p; *pp = %p; **pp = %d; zp = %p\n", pp, *pp, **pp, zp);
}

Expectations

  1. 3:pp is 4:pp is 5:pp.
  2. 3:*pp is 3:zp is null.
  3. 4:*pp is 1:xp is 4:zp.
  4. 5:*pp is 2:yp is 5:zp.
  5. 4:**pp is xp is 1.
  6. 5:**pp is yp is 2.
import ctypes
def main():
x = ctypes.c_int(1)
y = ctypes.c_int(2)
xp = ctypes.pointer(x)
yp = ctypes.pointer(y)
print('1: xp = {}; *xp = {}'.format(ptr(xp), xp.contents))
print('2: yp = {}; *yp = {}'.format(ptr(yp), yp.contents))
zp = ctypes.POINTER(ctypes.c_int)()
pp = ctypes.pointer(zp)
print('3: pp = {}; *pp = {}; zp = {}'.format(ptr(pp), ptr(pp.contents), ptr(zp)))
pp[0] = xp
print('4: pp = {}; *pp = {}; **pp = {}; zp = {}'.format(ptr(pp), ptr(pp.contents), pp.contents.contents, ptr(zp)))
pp[0] = yp
print('5: pp = {}; *pp = {}; **pp = {}; zp = {}'.format(ptr(pp), ptr(pp.contents), pp.contents.contents, ptr(zp)))
def ptr(pointer):
'''Format a pointer into a string.'''
return ptr1(pointer)
#return ptr2(pointer)
def ptr1(pointer):
address = ctypes.cast(pointer, ctypes.c_void_p).value
if address is None:
return '(null)'
else:
return '{:#018x}'.format(address)
def ptr2(pointer):
address = ctypes.addressof(pointer)
if address is None:
return '(null)'
else:
return '{:#018x}'.format(address)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment