I\'m doing an exercise in which I need to print the memory (address) of a pointer. It would be easy to do it with printf(\"%p\", ..)
but I\'m not allowed to use
You could do something like this... You said printf()
is off limits, but you said nothing about sprintf.
print_bytes(char *ptr, int count)
{
int i;
char string[1024];
string[0] = 0;
for(i = 0; i < count; i++)
{
sprintf(string,"%s %2x", string, *(ptr+i));
}
puts(string);
}
This should loop through count
bytes printing out each hexadecimal byte starting from the passed in address in ptr
.
Obviously, this makes no attempt to properly size the string array. That should be dynamically sized based on the passed in count.
To substitute write()
for puts()
, you could use:
write(1, string, strlen(string)); /* 1 = STDOUT */