How do I dereference based on size?
I am trying to print the value pointed to by an address but the problem is I need to dereference this pointer based on the size that is passed to me. So something of this sort:
void print(Address addr, Int size) {
...
}
I am a little confused on how to achieve this. Can someone point me in the right direction?
EDIT: Ok so I'm thinking:
char p[80];
memset(p, '\0', 80);
memcpy(p, addr, size);
开发者_开发技巧
And then dereference as *p. If there is a better way or a correct way, please let me know
Your question is very unclear. If you mean you want to dump arbitrary binary data from the address passed, you want something like:
void print(const unsigned char *addr, size_t size)
{
while (size--) printf("%.2x", *addr++);
}
Or if you mean you want to print character data that's not null-terminated, try:
void print(const char *addr, int size)
{
printf("%.*s", size, addr);
}
If it is a number, which I assume it is, you will need something like this:
int n=0;
if (size>sizeof(int)) { return; //int is too small };
for (int i=0;i<size;i++) {
((char*)(&n))[sizeof(int)-(i+1)] = ((char*)addr)[size-(i+1)];
}
printf("%d",n);
You may use a switch statement in the routine:
switch (size) {
case 1: print( *(char*)pointer); break;
case 2: print( *(short*)pointer); break;
case 4: print( *(long *)pointer); break;
case 8: print( *(__int64*)pointer); break;
default: puts( "unsupported);
}
("print" is a routine to print integers of various sizes, perhaps using C++ polymorphism)
A sophisticated solution is to use a C++ template e.g. using a parameter type Integer
which is subsituted by the actual variable type upon invocation. This routine may then act on the size of this Integer
variable (which may vary from 1 to 8, or more if you implement longer integers yourself). This disadvantage of this approach is that the compiler generates a routine instance for every type of argument, and logic dependent on the size will lead to "always true" conditions for some tests. An easy way out is to use always the longest type of integer you'd expect.
精彩评论