且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类型将字符指针转换为整数指针

更新时间:2023-01-16 17:31:50

既然指针是强类型的,那么字符指针不应该严格指向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.