类型转换char指针到整数指针 [英] Type casting char pointer to integer pointer

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

问题描述

因此,我看到了一些有关如何找到体系结构字节序的示例.假设我们有一个指向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打印字符吗?

这里还有另外一件事: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.

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

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