uint8_t * 和 char * 之间的转换。会发生什么?
当在这两者之间进行与终止字符相关的转换时会发生什么?在 C99 Objective-C 中。
What happens when casting between these two in relation to the termination character? In C99 Objective-C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这个答案中,我假设你的系统上的 char 是 8 位。
如果您的架构使用
unsigned char
作为char
类型,那么绝对不会发生任何事情。如果您的架构使用
signed char
作为char
类型,那么 char 的负值将回绕,从而可能导致意外结果。然而,对于终止空字符来说,这种情况永远不会发生。请注意,通过“强制转换”实际上不会发生任何事情,您只是告诉编译器以不同的方式解释内存中的某个位置。这种解释上的差异会产生演员阵容的实际(副作用)效果。
I assume that a char is 8 bits on your system in this answer.
If your architecture uses
unsigned char
aschar
type then absolutely nothing will happen.If your architecture uses
signed char
aschar
type then negative values of char will wrap around causing possibly unexpected results. This however will never happen to the termination null character.Please note, by "casting" nothing really happens, you just tell the compiler to interpret a certain location in the memory differently. This difference in interpretation would create the actual (side)effects of the cast.
如果 char 和 uint8_t 是兼容类型(它们应该在大多数当前的台式计算机上),则指向该类型对象的指针具有相同的表示和对齐要求,因此应该将一种转换(隐式或通过强制转换显式)转换为另一种没有问题。
同样,如果所指向的值兼容,则无论它们被解释为什么类型,都应同等对待。
注意:我不能 100% 确定
uint8_t
和char
在带签名字符的实现上兼容。如果类型不兼容,您将调用未定义的行为和任何事情都可能发生:很可能发生的事情是一切都按照您的预期“工作”——但不能保证它总是以同样的方式工作
If
char
anduint8_t
are compatible types (they should be on most current desktop computers), pointers to objects of that type have the same representation and alignment requirements, so there should be no problem converting (implicitly, or explicitly with a cast) one to the other.The values pointed to, again, if they are compatible, should be treated equally no matter what type they are interpreted as.
Note: I am not 100% certain that
uint8_t
andchar
are compatible on a implementation with signed chars.If the types are not compatible you invoke Undefined Behaviour and anything can happen: a very likely thing to happen is that everything "works" as you expect -- but there is no guarantee it will always work the same