Reputation: 185
the code works fine for an int but when I want to use a float it fails unless I cast the structure as a character pointer. Here's what it looks like:
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
Will not work for a float but casting location and the offset as an int pointer will.
I've tried looking online but I couldn't find much about the problem.
Upvotes: 4
Views: 451
Reputation: 12047
This is because pointers have 'units', the size of the objects they point to.
Lets assume you have a pointer p
that points to, say, address 1000.
if you have
int* p = 1000;
p += 10;
p
will point to 1040
on 32bit machines, because an int
has a size of 4 bytes.
But if you have
char* p = 1000;
p += 10;
p
will point to 1010
.
That's why
*(float *)((char *)location + offset) = imput;
works, but
*(float *)(location + offset) = imput Will Not Work
doesn't.
Upvotes: 5