【问题标题】:Using offsetof with a float in c在c中使用带有浮点数的offsetof
【发布时间】:2015-04-14 08:43:55
【问题描述】:

代码适用于 int,但是当我想使用 float 时它会失败,除非我将结构转换为字符指针。这是它的样子:

struct test
{
    float a;
    float b;
};

void stuff(int offset, test* location);

int main()
{
    test *t;
    t = (test*)malloc(sizeof(test));

    char choice = '\0';

    //Find the byte offset of 'a' within the structure
    int offset;
    printf("Edit a or b?");
    scanf("%c", &choice);
    switch (toupper(choice))
    {

    case 'A':
        offset = offsetof(test, a);
        stuff(offset, t);
        break;
    case 'B':
        offset = offsetof(test, b);
        stuff(offset, t);
        break;
    }
    printf("%f %f\n", t->a, t->b);
    return 0;
}

void stuff(int offset, test* location)
{
    float imput;
    printf("What would you like to put in it? ");
    scanf("%f", &imput);
    *(float *)((char *)location + offset) = imput;
    //*(float *)(location + offset) = imput   Will Not Work
}

*(float *)(location + offset)= imput 不适用于浮点数,但转换位置和作为 int 指针的偏移量。

我尝试在网上查找,但找不到太多关于此问题的信息。

【问题讨论】:

  • 这也不适用于整数。您需要转换为 char * 的原因是指针算法。当您不投射指针时,它会将offset * sizeof(test) 添加到您的指针地址,这不是您想要的。
  • 给出的示例无法编译。 test 可能缺少 typedef。鉴于此,没有一个答案是有用的。

标签: c offsetof


【解决方案1】:

这是因为指针具有“单位”,即它们指向的对象的大小。

假设您有一个指针 p,它指向例如地址 1000。

如果你有

int* p = 1000;
p += 10;

p 在 32 位机器上将指向 1040,因为 int 的大小为 4 个字节。

如果你有

char* p = 1000;
p += 10;

p 将指向1010

这就是为什么

*(float *)((char *)location + offset) = imput;

有效,但是

*(float *)(location + offset) = imput   Will Not Work

没有。

【讨论】:

    猜你喜欢
    • 2010-10-28
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2012-06-24
    相关资源
    最近更新 更多