Type casting char pointer to integer pointer

后端 未结 2 688
甜味超标
甜味超标 2020-12-05 21:44

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

相关标签:
2条回答
  • 2020-12-05 22:41

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

    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.

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

    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.

    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.

    0 讨论(0)
  • 2020-12-05 22:47

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

    This is kind of undefined behavior - but such that most sane implementations will do what you mean. So most people would say ok to it.

    And what's up with printing with %d?

    Format %d expects argument of type int, and the actual arg of type char is promoted to int by usual C rules. So this is ok again. You probably don't want to use %c since the content of byte pointed by p may be any byte, not always a valid text character.

    0 讨论(0)
提交回复
热议问题