C 编程类型转换和 sizeof()

C Programming type casting and sizeof()

当我键入 cast 并将 double 数据类型转换为 int 数据类型,然后我尝试打印要占用多少大小时,它显示了 int 大小,但在编译时它给了我警告 (gcc)。我想知道为什么它会给我警告以及如何摆脱这个警告。

我也尝试过使用结构,但编译时仍然显示警告。 cast.c:12:11: 警告:格式“%d”需要类型为“int”的参数,但参数 2 的类型为“long unsigned int”[-Wformat=] printf("%d\n",sizeof(cast)); ~^ %ld

#include <stdio.h>

int main(void){
    double n=0;
    //  int x=0;
    int cast;
    cast = (int) n;
    printf("%d\n",sizeof(cast));
    return 0;
}

我希望找出它显示警告的原因。

sizeof 产生类型 size_t 的值。正确的打印方式是 %zu:

printf("%zu\n", sizeof cast));

z是针对size_t类型的修饰符,u是针对unsigned的,因为size_t是unsigned。 (%d 用于签名 int。)