简体   繁体   English

数据类型之间c的类型转换

[英]typecasting in c between data types

I wrote this small code to test my understanding. 我写了这个小代码来测试我的理解。 But didn't understand some facts behind it. 但不了解背后的事实。 I am working on a 64 bit little endian machine. 我正在使用64位小字节序机器。 So any pointer is 8 bytes. 所以任何指针都是8个字节。 That means 那意味着

#include<stdio.h>
int main(){
    char *c = (char *)0x12345678889;
    long a = 1;
    int b = (long)(c-a);
    /* int cc = (int)(c-a); gives compiler error */
    printf("val = %x and b = %x", c-a,b);
    return 0;
}
Output
val = 45678888 and b = 45678888

Say the starting address is 100. So the char* would be stored in memory as 100->89, 101->88 ... 105->12 and bytes 106 and 107 will be unused. 假设起始地址为100。因此char*将以100-> 89、101-> 88 ... 105-> 12的形式存储在内存中,并且字节106和107将不被使用。 Is this assumption of mine correct in the first place? 我的这种假设首先正确吗? Since int and long are 4 bytes in a 64 bit machine, it will start from 100,101,102 and 103 and will consider only these bytes. 由于int和long在64位计算机中为4个字节,因此它将从100,101,102和103开始,并且仅考虑这些字节。 So 45678889 - 1 = 45678888. Is my understanding correct? 所以45678889-1 =45678888。我的理解正确吗? Finally, I don't understand while the commented line gives a compiler error. 最后,我不明白注释行给出了编译器错误。 The compiler had implicitly typecasted the above line. 编译器已隐式地转换了上面的行。 But why not below? 但是为什么不低于?

First you didn't know a-priori how values are stored, it depends on machine endianess . 首先,您不了解先验值的存储方式,这取决于机器的耐久性 Values can be stored from lowest to highest digits or in the converse. 值可以从最低到最高数字存储,也可以相反存储。 Yours is from low to high. 您的排名从低到高。

Second, on many 64-bit machines int are 4 bytes long and long 8 bytes long. 其次,在许多64位计算机上,int长4个字节,长8个字节。 What happens is that your machine computes ca which is 0x12345678888 of type (char *) , then it convert it into a long with value 0x12345678888 and then truncate it silently (longs are silently converted to ints in C). 什么情况是,你的机器计算ca0x12345678888类型(char *)然后将其转换成一个long与价值0x12345678888 ,然后截断它静静地(多头正在悄悄转换为整数在C)。

The comment gives a warning because ca is of type char * and that cannot be silently converted into an int (it is considered much dangerous dans long to int). 该注释发出警告,因为cachar *类型,并且无法将其静默转换为int (认为int很危险,dans很危险)。 Ok then you converted it explicitly but the compiler warns you that it is dangerous too. 好的,然后您对其进行了显式转换,但是编译器警告您它也很危险。 Note that these are warnings not errors (it may depend on compiler options...). 请注意,这些只是警告而非错误(可能取决于编译器选项...)。

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

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