简体   繁体   English

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

[英]Print Integer value using character pointer in c

I have a small doubt on typecasting.我对类型转换有一点疑问。 Here I am pasting my sample code.我在这里粘贴我的示例代码。

#include <stdio.h>

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

I have typecast at two points.我在两点进行了类型转换。 First one is,第一个是,

char *ptr=(char*)&i;

Second one is ,第二个是,

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

in order to avoid the compilation warnings.以避免编译警告。

When I print it I got the output as当我打印它时,我得到的输出为

Value of int =76

I know the fact that we need to assign the address of values to the proper type of pointers in order to deference it properly.我知道我们需要将值的地址分配给正确类型的指针以便正确地尊重它。

My doubt is,我的疑问是,

  1. Is it possible to print the value 1100 using character pointer ?是否可以使用字符指针打印值 1100 ? If Yes then how ?如果是,那么如何?

I expect a clear cut answer from you folks.我期待你们这些人的明确答复。 Please help on this.请帮忙解决这个问题。

In your code, you're casting after it already dereferenced the pointer, so it will just cast a char .在您的代码中,您它已经取消引用指针之后进行转换,因此它只会转换为char Cast the pointer first, like this:首先投射指针,如下所示:

*((int*)ptr)

But still, this is a non-recommended strategy.但是,这仍然是一个不推荐的策略。 If you want a really universal pointer type, use void* which will not allow dereferencing while it is not casted.如果您想要一个真正通用的指针类型,请使用void* ,它在未强制转换时不允许取消引用。

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

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