gpt4 book ai didi

c - 在 C 中重新解释内存的正确方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 15:29:40 25 4
gpt4 key购买 nike

很久以前,我已经数不清在 C 语言中做过这样的事情的次数了:

struct foo f;
struct foo* pf = &f;
char* pc = (char*) pf;
transmit(pc, sizeof(f));

或者也许:

char* buffer[1024];
receive(buffer, 1024);
float values[256];
for(int ii = 0; ii < 256; ii++) {
float* pf = (float*)(buffer + ii*4);
values[ii] = *pf;
}

或者也许:

uint32_t ipAddress = ...;
uint8_t* p = (uint8_t*)&ipAddress;
uint8_t octets[4] = {p[0], p[1], p[2], p[3]};
printf("%d.%d.%d.%d\n", octets[0], octets[1], octets[2], octets[3]);

我刚刚发现,通过强制转换为另一种指针类型来重新解释这样的一段内存会调用未定义的行为。然而,上述所有示例都是绝对必要的。正确的做法是什么?

最佳答案

转换为 char *(或 unsigned char * 或其 typedef)是一种特殊情况,不会导致未定义的行为。

来自 C 规范,6.3.2.3 指针,第 7 段:

When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.

本案例涵盖了您的第一个和第三个示例。第二个例子有点古怪,但可能适用于大多数系统。您真正应该做的是直接读取:

float values[256];
receive(values, sizeof values); // assuming receive() takes a "void *" parameter

或者类似这样的东西(以避免对齐问题):

char buffer[1024];
receive(buffer, sizeof buffer);
float values[256];
for(int i = 0; i < 256; i++)
{
char *pf = (char *)&values[i];
memcpy(pf, buffer + i * sizeof(float), sizeof(float));
}

(请注意,我将 buffer 更改为 char 数组 - 我认为这是您问题中的错字)。

关于c - 在 C 中重新解释内存的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17348839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com