Pointer address Arithmetic and Hex/Dec Conversion

2019-08-03 22:27发布

问题:

I have a pointer address I obtained from the extern char etext, end and edata. I also obtained address of variables using &<Variable Name>. Both are hexadecimal pointer addresses.

I need to do arithmetic on those addresses in decimal. How do I do so? I need to convert the address into an int in decimal so I can find size of memory segments by subtracting addresses.

回答1:

Math is math. It doesn't matter what base you do it on. The computer is working only in base 2 anyway. Only during input or output does base matter. Bytewise arithmetic on pointers is possible if you interpret them as char * pointers:

ptrdiff_t segmentSize = (char *)segmentEndAddress - (char *)segmentStartAddress;

printf("Segment size in base 10: %td\n", segmentSize);
printf("Segment size in base 16: %tx\n", segmentSize);
printf("Segment size in base  8: %to\n", segmentSize);


回答2:

You can do arithmetic with pointers. Only be aware that the "unit" is not 1 but the size of the pointed object. So if p is a pointer to integer the difference in addresses between p+1 and p could be 4 bytes or more.

If you want to do arithmetic with addresses you should use pointers to char or convert them to such pointers.



回答3:

There is no "hexadecimal variables", rather variables that you can print in some representation. Moreover, the standard does not guarantee that an int can hold a pointer object. If you use C99 or C11, it is possible to use the optional type (u)intptr_t to do this.

uintptr_t n = (uintptr_t)(void *)etext;


回答4:

Both are hexadecimal pointer addresses...I need to do arithmetic on those addresses in decimal. How do I do so?

Decimal and hexadecimal are just representations... ways to display the number. But whether I write 10 or 0xA, they're still the same number. A pointer is a number, and you can represent that number in decimal or hexadecimal, but it's still just a number. So, you can do something like:

char *foo = "A dog and a cat";
int offset = 4;
char fifthChar = *(foo + offset);

Basically, you're adding 4 to the pointer foo and dereferencing the result, so that fifthChar will hold the character 'g'.