类型将字符指针转换为整数指针 [英] Type casting char pointer to integer pointer

查看:55
本文介绍了类型将字符指针转换为整数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我看到了一些关于如何找到架构的字节序的例子.假设我们有一个指向 int 数据类型的整数指针.假设 int 值为 0x010A0B12.在小端架构中,最低有效字节,即 12,将存储在最低内存地址中,对吗?所以 4 字节整数中的最低字节将是 12.

So I saw a few example on how the endianness of an architecture could be found. Let's say we have an integer pointer that points to an int data type. And let's say the int value is 0x010A0B12. In a little endian architecture, the least significant byte, i.e, 12, will be stored in the lowest memory address, right? So the lowest byte in a 4-byte integer will be 12.

现在开始检查.如果我们声明一个 char 指针 p,并将整数指针类型转换为 char * 并将其存储在 p 中,并打印 p 的解引用值,我们将获得有关架构字节序的线索.如果是 12,我们就是小端;01 表示大端.这听起来真的很整洁...

Now, on to the check. If we declare a char pointer p, and type cast the integer pointer to a char * and store it in p, and print the dereferenced value of p, we will get a clue on the endianness of the architecture. If it's 12, we're little endian; 01 signifies big endian. This sounds really neat...

int a = 0x010A0B12;
int *i = &a;
char *p = (char*)i; 
printf("%d",*p); // prints the decimal equivalent of 12h!

这里有几个问题,真的.由于指针是强类型的,字符指针不应该严格指向 char 数据类型吗?用 %d 打印是怎么回事?对于字符,我们不应该用 %c 打印吗?

Couple of questions here, really. Since pointers are strongly typed, shouldn't a character pointer strictly point to a char data type? And what's up with printing with %d? Shouldn't we rather print with %c, for character?

推荐答案

既然指针是强类型的,那么字符指针不应该严格指向char数据类型吗?

Since pointers are strongly typed, shouldn't a character pointer strictly point to a char data type?

C 有一个规则,任何指针都可以安全地转换为 char*void*.因此,允许将 int* 转换为 char*,并且它也是可移植的.指针将指向 int 内部表示的初始字节.

C has a rule that any pointer can be safely converted to char* and to void*. Converting an int* to char*, therefore, is allowed, and it is also portable. The pointer would be pointing to the initial byte of your int's internal representation.

我们不应该用 %c 打印字符吗?

Shouldn't we rather print with %c, for character?

这里还有另一件事:printf 的可变长度参数列表.当您将 char 传递给 printf 的无类型参数时,默认转换适用:char 被转换为 int.这就是为什么 %d 格式可以很好地处理数字,并按照您的预期打印出来.

Another thing is in play here: variable-length argument list of printf. When you pass a char to an untyped parameter of printf, the default conversion applies: char gets converted to int. That is why %d format takes the number just fine, and prints it out as you expect.

您也可以使用 %c.处理%c 说明符的代码将参数读取为int,然后将其转换为char.不过,0x12 是一个特殊字符,因此您不会看到它的统一打印输出.

You could use %c too. The code that processes %c specifier reads the argument as an int, and then converts it to a char. 0x12 is a special character, though, so you would not see a uniform printout for it.

这篇关于类型将字符指针转换为整数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆