在c中使用字符指针打印整数值

Print Integer value using character pointer in c

我对类型转换有一点疑问。我在这里粘贴我的示例代码。

#include <stdio.h>

int main()
{
    int i=1100;
    char *ptr=(char*)&i;
    
    printf("Value of int =%d\n",(int*)(*ptr));
    return 0;
}

我在两点上进行了类型转换。 第一个是,

char *ptr=(char*)&i;

第二个是,

printf("Value of int =%d\n",(int*)(*ptr));

为了避免编译警告。

打印时得到的输出为

Value of int =76

我知道我们需要将值的地址分配给正确类型的指针才能引用它 正确。

My doubt is,

  1. Is it possible to print the value 1100 using character pointer ? If Yes then how ?

我希望你们能给出明确的答案。 请帮忙解决这个问题。

在您的代码中,您在 之后转换 它已经取消引用指针,因此它只会转换 char。先投指针,像这样:

*((int*)ptr)

但是,这仍然不是推荐的策略。如果你想要一个 really 通用指针类型,请使用 void*,它在未转换时不允许取消引用。