Pointer address Arithmetic and Hex/Dec Conversion

耗尽温柔 提交于 2020-01-16 00:57:29

问题


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'.



来源:https://stackoverflow.com/questions/14549551/pointer-address-arithmetic-and-hex-dec-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!