简体   繁体   English

可以将int指针强制转换为char *吗?

[英]Can int pointer be casted to char *?

The below program tests for Little/Big endian on intel processor. 下面的程序在Intel处理器上测试Little / Big Endian。 Actually little endian is correct output. 实际上,小字节序是正确的输出。 First I am casting int to char* and accessing its value without initialization to int * .I am not understanding second part of output. 首先,我将intchar*并在不初始化为int *情况下访问其值。我不理解输出的第二部分。 Here int pointer is casted to char * . 这里的int指针被强制转换为char * So why is not int pointer not changed its alignment to char * ? 那么为什么不将int指针的对齐方式更改为char *

00000000 00000000 00000011 01111111 = 895
0        0         3       127

int main() {
    int num = 895;
    if(*(char *)&num == 127)
    {
        printf("\nLittle-Endian\n");
    }
    else
    {
        printf("Big-Endian\n");
    }

    int *p = (char *)&num ;
    if(*p == 127)
    {
        printf("\nLittle-Endian\n");
    }
    else
    {
        printf("Big-Endian\n");
    }
    printf("%d\n",*p);
}

o/p

Little-Endian
Big-Endian
895
  1. The first half of your program using this comparison: 程序的前半部分使用此比较:

     if(*(char *)&num == 127) 

    looks fine. 看起来不错。

  2. The second half of your program contains this assignment: 程序的后半部分包含以下任务:

     int *p = (char *)&num ; 

    Which isn't valid code. 无效的代码。 You can't convert pointer types without an explicit cast. 如果没有显式强制转换,则无法转换指针类型。 In this case, your compiler might be letting you get away with it, but strictly speaking, it's incorrect. 在这种情况下,您的编译器可能会让您无法使用它,但是严格来说,这是不正确的。 This line should read: 该行应显示为:

     int *p = (int *)(char *)# 

    or simply this equivalent statement: 或只是以下等效语句:

     int *p = # 

    From this example, I'm sure you can see why your second test doesn't work the way you'd like it to - you're still operating on the whole int , not on the single byte you were interested in. If you made p a char * , it would work the way you expected: 从此示例中,我确定您可以看到为什么第二个测试无法按您希望的方式工作-您仍然在整个int上进行操作,而不是对您感兴趣的单个字节进行操作。将p char * ,它将按照您期望的方式工作:

     char *p = (char *)# 

Can int pointer be cast to char * ? 可以将int指针强制转换为char *吗?

Yes, it's only the inverse that would invoke undefined behavior, more precisely, using the result of a cast from char * to int * (since char is 1-byte aligned, so any data pointer type can safely be cast to char * ). 是的,只有使用int *char *int *的结果才能调用未定义的行为(因为char是1字节对齐的,所以任何数据指针类型都可以安全地转换为char * )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM