[英]Typecasting the Reference of a Double Variable
I have a question about typecasting the reference of a variable of type double.我有一个关于对 double 类型变量的引用进行类型转换的问题。 What is exactly happening when &d
becomes typecasted into an unsigned char*
?当&d
被类型转换为unsigned char*
时到底发生了什么? How is typecasting the address of a variable valid and what is it actually doing?类型转换变量的地址如何有效,它实际上在做什么?
#include <stdio.h>
int main(void) {
// examining object representation is a legitimate use of cast
double d = 3.14;
printf("The double %.2f(%a) is: ", d, d);
for(size_t n = 0; n < sizeof d; ++n)
printf("0x%02x ", ((unsigned char*)&d)[n]); // <--
}
And how do the array brackets work in this case?在这种情况下,数组括号如何工作?
&d
represents a pointer to the location at which the value of the double is stored. &d
表示指向存储双精度值的位置的指针。 A pointer is simply a memory address (likely a 64-bit value) which identifies a location in memory, regardless of the type of data that is being pointed to.指针只是一个 memory 地址(可能是一个 64 位值),它标识 memory 中的一个位置,而与所指向的数据类型无关。
This makes the cast from a double *
to an unsigned char *
possible as the representation of both is simply a word of memory.这使得从double *
到unsigned char *
的转换成为可能,因为两者的表示只是 memory 的一个字。 The array notation then dereferences this pointer and adds n times the size of a char (1 byte), and then reads the next char-many bits.然后数组表示法取消引用该指针并添加 n 倍 char 大小(1 字节),然后读取下一个 char-many 位。
The array notation a[n]
is equivalent to *(a+n)
.数组符号a[n]
等价于*(a+n)
。 It is simply adding an offset to the pointer referred to by a
.它只是将偏移量添加到由a
引用的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.