2015-04-14 33 views
4

該代碼適用於int,但是當我想使用浮點數時,它將失敗,除非我將該結構作爲字符指針進行投射。這裏是什麼樣子:在c中使用浮點數offsetof

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指針。

我試過在網上找,但我找不到太多的問題。

+3

這也不適用於整數。你需要轉換成char *的原因是因爲指針算術。當你離開指針的時候,它會把'offset * sizeof(test)'加到你指針地址,而不是你想要的。 – JS1

+0

給出的示例不能編譯。也許缺少'test'的typedef。鑑於此,沒有任何答案是有用的。 –

回答

5

這是因爲指針有'單位',它們指向的對象的大小。

假設您有一個指針p指向,也就是說,地址1000

,如果你有

int* p = 1000; 
p += 10; 

p將指向1040在32位的機器,因爲int的大小爲4字節。

但如果你有

char* p = 1000; 
p += 10; 

p將指向1010

這就是爲什麼

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

作品,但

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

沒有。