铸造一个指针 - 是什么在运行时的区别? [英] Casting a pointer - What is the difference at runtime?

查看:101
本文介绍了铸造一个指针 - 是什么在运行时的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的小例子code:

Consider the following small example code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *i;
    char *c1, *c2;

    i = malloc(4);

    *i = 65535;

    c1 = i;
    c2 = (char *)i;

    printf("%p %p %p\n", i, c1, c2);
    printf("%d %d", *c1, *c2);

    free(i);

    return 0;
}

在这个例子中,我分配的内存来存储一个整数,这是由指出我。然后,我存储在值65535(1111 1111 1111 1111)* I 。接下来我要做的事情就是让两个的char * 指针也指向整数。我这样做两次,但在两种不同的方式: C1 = I; C2 =(字符*)我; 。最后,我在打印屏幕上的所有指针和所有值。这三个指针指向同一个地址,这两个值 * C1 * C2 是正确的 (-1)

In the example, I allocate memory to store an integer, which is pointed by i. Then, I store the value 65535 (1111 1111 1111 1111) in *i. The next thing I do is make two char* pointers also point to the integer. I do it two times, but in two different ways: c1 = i; and c2 = (char *)i;. Finally, I print all pointers and all values in the screen. The three pointers are pointing to the same address, and the two values *c1 and *c2 are correct (-1).

然而,编译器生成该行警告: C1 = I; 。生成警告,因为我没有使用(字符*)投做分配。

However, the compiler generates a warning in this line: c1 = i;. The warning is generated because I did not use the (char *) cast to do the assignment.

我想什么要问的是的为什么编译器生成此警告,因为我没有看到的任何区别使用 C1 = I ;或 C2 =(字符*)我; 。在这两种情况下,结果是,在字节大小相同的同一地址。这是适用于所有的演员,哪怕是一个(INT *)投,(浮点*)投,(简称*)投,等他们都产生相同的值,但是编译器将只接受它而不发出警告,如果正在使用的铸铁是指针的类型

What I would like to ask is why the compiler generates this warning, since I do not see any difference in using c1 = i; or c2 = (char *)i;. In both cases, the result is the same address with the same size in bytes. And this is valid for all casts, even if it is a (int *) cast, (float *) cast, (short *) cast, etc. All of them generate the same value, but the compiler will only accept it without a warning if the cast being used is of the pointer's type.

我真的想知道为什么编译器要求该投,即使结果总是相同的。

I really would like to know why the compiler asks for that cast, even if the result is always the same.

推荐答案

当您使用

c2 = i;

编译器警告您关于类型的分配为int * 的char * 。这可能是无心之失。编译器警告您,希望,如果它确实是无心之失,你要修复它的机会。

the compiler warns you about the assignment of type int* to char*. It could potentially be an inadvertent error. The compiler is warning you with the hope that, if it is indeed an inadvertent error, you have the chance to fix it.

当您使用

c2 = (char *)i;

你告诉编译器,你,作为程序员,知道自己在做什么。

you are telling the compiler that you, as the programmer, know what you are doing.

这篇关于铸造一个指针 - 是什么在运行时的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆