该代码适用于 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 指针的偏移量会。
我试过在网上找,但我找不到太多关于这个问题的信息。