[英]strtoul() not working as expected?
I am trying to convert a string such as "0x7ffd01767a60" to hexadecimal so I can compare pointers.我正在尝试将诸如“0x7ffd01767a60”之类的字符串转换为十六进制,以便我可以比较指针。 Not sure if this is the best decision.不确定这是否是最好的决定。
I am doing this:我正在这样做:
char *address = "0x7ffd01767a60";
strtol(address,NULL,16);
printf("%lp",address);
And I am getting this: 0x7ffd01764120我得到这个:0x7ffd01764120
EDIT: It seems I was printing the string address ignoring the function return.编辑:似乎我正在打印字符串地址而忽略函数返回。 Thanks Jens!谢谢詹斯! and schlenk.和 schlenk。
SOLVED!解决了! This is what I do这就是我所做的
char *address = "0x7ffd01767a60";
void *p;
unsigned long int address_hex = strtol(address,NULL,16);
p = (void*) address_hex;
printf("%p",p);
printf prints the same memory address. printf 打印相同的内存地址。
You're printing the address of the string itself while ignoring the result of the strtoul() function call.您正在打印字符串本身的地址,同时忽略strtoul()函数调用的结果。 This should work:这应该有效:
const char *address = "0x7ffd01767a60";
unsigned long int address_hex = strtoul(address, NULL, 16);
// Check for errors in errno
printf("%lx\n", address_hex);
Also, personally I prefer code to be as explicit as possible which is why I passed 16
as the base parameter.此外,我个人更喜欢代码尽可能明确,这就是我传递16
作为基本参数的原因。
Note: Please read the documentation on the return value, to make sure that you identify errors correctly.注意:请阅读有关返回值的文档,以确保正确识别错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.