取消引用一个指针

取消引用一个指针

本文介绍了在 C 中,如果我投 &取消引用一个指针,我先做哪个重要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在 C 中,您可以转换简单的数据类型,例如 intfloat 和指向这些类型的指针.

In C, you can cast both simple data types like int, float, and pointers to these.

现在我假设如果你想从一个指向一种类型的指针转​​换成另一种类型的值(例如从 *floatint),强制转换和取消引用的顺序无关紧要.IE.对于变量 float* pf,你有 (int) *pf == *((int*) pf).有点像数学中的交换性......

Now I would have assumed that if you want to convert from a pointer to one type to the value of another type (e.g. from *float to int), the order of casting and dereferencing does not matter. I.e. that for a variable float* pf, you have (int) *pf == *((int*) pf). Sort of like commutativity in mathematics...

然而,情况似乎并非如此.我写了一个测试程序:

However this does not seem to be the case. I wrote a test program:

#include <stdio.h>
int main(int argc, char *argv[]){
  float f = 3.3;
  float* pf = &f;
  int i1 = (int) (*pf);
  int i2 = *((int*) pf);
  printf("1: %d, 2: %d
", i1, i2);
  return 0;
}

在我的系统上输出是

1: 3, 2: 1079194419

因此,转换指针似乎与转换值的工作方式不同.

So casting the pointer seems to work differently from casting the value.

这是为什么?为什么第二个版本没有做我认为应该做的事情?

Why is that? Why does the second version not do what I think it should?

这是依赖于平台的,还是我以某种方式调用了未定义的行为?

And is this platform-dependent, or am I somehow invoking undefined behaviour?

推荐答案

下面说的是获取 pf 处的浮点数并将其转换为整数.这里的转换是将浮点数转换为整数的请求.编译器生成代码以将浮点值转换为整数值.(将浮点值转换为整数是一件正常"的事情.)

The following says get the float at pf and convert it to an integer. The casting here is a request to convert the float into an integer. The compiler produces code to convert the float value to an integer value. (Converting float values to integers is a "normal" thing to do.)

int i1 = (int) (*pf);

下面说首先强制编译器认为 pf 指向一个整数(并忽略 pf 是指向浮点数的指针这一事实),然后获取整数值(但它不是整数值).这是一件奇怪而危险的事情.在这种情况下,强制转换会禁用正确的转换.编译器在内存中执行位的简单复制(产生垃圾).(也可能存在内存对齐问题!)

The following says first FORCE the compiler to think pf points to an integer (and ignore the fact that pf is a pointer to a float) and then get the integer value (but it isn't an integer value). This is an odd and dangerous thing to do. The casting in this case DISABLES the proper conversion. The compiler performs a simple copy of the bits at the memory (producing trash). (And there could be memory alignment issues too!)

int i2 = *((int*) pf);

在第二个语句中,您不是在转换"指针.您是在告诉编译器内存指向什么(在本例中,错误).

In the second statement, you are not "converting" pointers. You are telling the compiler what the memory points to (which, in this example, is wrong).

这两个语句做了非常不同的事情!

These two statements are doing very different things!

请记住,c 有时使用相同的语法来描述不同的操作.

Keep in mind that c some times uses the same syntax to describe different operations.

==============

=============

请注意,double 是 C 中的默认浮点类型(数学库通常使用双参数).

Note that double is the default floating point type in C (the math library typically uses double arguments).

这篇关于在 C 中,如果我投 &amp;取消引用一个指针,我先做哪个重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 10:03