代码适用于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
}
Run Code Online (Sandbox Code Playgroud)
*(float *)(location + offset)= imput
不适用于浮点数而是投射位置和偏移量作为int指针.
我试过在线看,但我找不到太多问题.
这是因为指针具有'单位',即它们指向的对象的大小.
让我们假设您有一个指向p地址1000 的指针.
如果你有
int* p = 1000;
p += 10;
Run Code Online (Sandbox Code Playgroud)
p将指向104032位机器,因为int它的大小为4个字节.
但如果你有
char* p = 1000;
p += 10;
Run Code Online (Sandbox Code Playgroud)
p会指出1010.
这就是为什么
*(float *)((char *)location + offset) = imput;
Run Code Online (Sandbox Code Playgroud)
有效,但是
*(float *)(location + offset) = imput Will Not Work
Run Code Online (Sandbox Code Playgroud)
没有.