是否可以在C中的UINT64_T指针中下注?
我是C初学者。很难理解此代码发生的事情:
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint64_t num = 99999;
uint64_t *num_ptr = #
uint8_t first_byte = ((uint8_t *)num_ptr)[0];
printf("%hhu", first_byte);
return 0;
}
此打印159
。
我正在查看uint8_t first_byte =(((uint8_t *)num_ptr)[0];
我试图以这种方式理解它:uint64_t指针num_ptr
首先是铸造作为UINT8_T指针,我们用方括号将其索引为第一个字节。这是正确的解释吗?如果是这样,是否可以将其划分为指针,以获取其部分内容而不取消给出。
I'm a C beginner. Having trouble understanding whats happening with this code:
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint64_t num = 99999;
uint64_t *num_ptr = #
uint8_t first_byte = ((uint8_t *)num_ptr)[0];
printf("%hhu", first_byte);
return 0;
}
This prints 159
.
I'm looking at uint8_t first_byte = ((uint8_t *)num_ptr)[0];
I'm trying to understand it this way: the uint64_t pointer num_ptr
is first cast as a uint8_t pointer, then we index into it with the square brackets to get the first byte. Is this a correct explanation? If so is it possible to index into pointers to get their partial contents without dereferencing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
99999
=0x1869f
,或者如果您将作为64位数字0000 0000 0000 0001 869F
9f86 0100100 0000 0000
。uint8_t
是所有非外观系统上的字符类型。(((uint8_t *)num_ptr)[0];
将64位指针转换为8位(字符)指针,然后使用[]
运算符来删除Reference指针。0x9f
= 159 dec。%hhu
用于打印无符号char
。用于uint8_t
的最正确的转换说明符,否则将是“%” priu8
来自inttypes.h
99999
=0x1869F
or if you will as a 64 bit number0000 0000 0001 869F
9F86 0100 0000 0000
.uint8_t
is a character type on all non-exotic systems.((uint8_t *)num_ptr)[0];
Converts the 64 bit pointer to a 8 bit (character) pointer and then uses the[]
operator to de-reference that pointer.0x9F
= 159 dec.%hhu
is used to printunsigned char
. The most correct conversion specifier to use foruint8_t
would otherwise be"%" PRIU8
frominttypes.h
考虑一个类似工作的程序:
输出:
在此处使用 c unigon ,它正在模拟它OP代码中所做的。
.parts
涵盖与Whole
的内存相同。因此,从本质上讲,parts
正在访问uint64_t
的字节内存中的内容,而无需任何指针删除。由于 endianness ,因此这种操作将存在具有可移植性问题的问题。当然,可以通过将
htonl()
之类的函数包装到网络字节顺序中来缓解这种情况,因此保留了已知顺序。Consider a work-alike program:
Which outputs:
Here with a C union, it's simulating what was done in the OP's code. The
.parts
covers the same memory as the.whole
. So in essence theparts
is giving access to the content of theuint64_t
's bytes-in-memory without any sort of pointer dereference.This sort of operation will have issues with portability due to endianness, and should generally be avoided. Of course one could mitigate this by packing into network-byte-order with functions like
htonl()
, so a known order is preserved.char
s访问其他数据时,就可以了。最安全的方法是使用
memcpy
char
s it is OK.The safest method is to use
memcpy