c - 将int32存储在int8指针中

标签 c pointers

在下面的代码片段中,我定义了 foo ,它足够大以容纳 32 位整数。但是,当我尝试在 foo 中存储 32 位整数时,它不适合。

int8_t * foo = malloc(sizeof(int32_t));
int32_t value = 300;
foo[0] = value;
printf("%i ", foo[0]); // 44

是否有某种方法可以使用更多元素来存储值而不是截断它?

最佳答案

foo[0]类型为int8_t ,所以它只够 1 个字节。

虽然相邻字节 ( foo[1], foo[2], foo[3] ) 可用,但编译器不知道您打算在仅使用 foo[0] 时复制所有 4 个字节。 .

相反:

*((int32_t*)foo) = 300;

其中表示,“假设 foo 是 4 字节整数的开头,然后为其分配值 300”

关于c - 将int32存储在int8指针中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54032110/

相关文章:

c - spoj ARRAYSUB : tried sliding window algorithm, 不接受

c - 简单的C指针混淆

C |指针、数组和分段问题

c - c中的指针类型转换

c - 在结构体中设置 const char 指针

c - 为什么 I2C_SMBUS_BLOCK_MAX 被限制为 32 字节?

将命令通过管道传递到 shell 后,C 无限循环

负零的 C 标准(1 的补码和有符号幅度)

c++ - 作为类成员的 2D vector 指针

c - 指针和结构的段错误