2013-03-07 87 views
-1

我是編程的新手,在事件中遇到了這個代碼片斷,這段代碼究竟做了什麼? 在此先感謝。訪問和存儲結構元素

#include <stdio.h> 
#define OFFSETOF(TYPE,ELEMENT) ((size_t)&(((TYPE *)50)->ELEMENT)) 
typedef struct PodTag 
{ 
char i; 
int d; 
int c; 
} PodType; 
int main() 
{ 
    printf("%d\n", OFFSETOF(PodType,c)); 
    printf("%d\n", OFFSETOF(PodType,d)); 
    printf("%d\n", OFFSETOF(PodType,i)); 
    printf("%d \n %d",(&((PodType*)0)->d),sizeof(((PodType*)0)->i)); 
    getchar(); 
    return 0; 
} 
+0

當這是C(沒有類)時,爲什麼要標記'class-members'? – m0skit0 2013-03-07 17:00:18

+0

你編譯並運行它看到它嗎? – 2013-03-07 17:03:01

回答

5

此代碼演示結構是如何存儲在內存中的C.

的代碼將被更好地寫成這樣:

#include <stdio.h> 

#define OFFSETOF(TYPE,ELEMENT) ((size_t)&(((TYPE *)100)->ELEMENT)) 

typedef struct PodTag { 
    char c; 
    int i; 
    int j; 
} PodType; 

int main() 
{ 
    printf("The size of a char is %d\n", sizeof(((PodType*)0)->c)); 
    printf("The size of an int is %d\n", sizeof(((PodType*)0)->i)); 
    printf("The size of a PodType is %d\n", sizeof(PodType)); 
    printf("The size of a pointer to a PodType is %d\n\n", sizeof(PodType*)); 

    printf("If there was a PodType at location 100, then:\n"); 
    printf(" the memory location of char c would be: %d\n", 
     OFFSETOF(PodType,c)); 
    printf(" the memory location of int i would be: %d\n", 
     OFFSETOF(PodType,i)); 
    printf(" the memory location of int j would be: %d\n", 
     OFFSETOF(PodType,j)); 

    return 0; 
} 

這段代碼的輸出是:

The size of a char is 1 
The size of an int is 4 
The size of a PodType is 12 
The size of a pointer to a PodType is 8 

If there was a PodType at location 100, then: 
    the memory location of char c would be: 100 
    the memory location of int i would be: 104 
    the memory location of int j would be: 108 
+0

+1爲你的答案,不應該3 printf語句打印sizeof(struct PodTag)?? – 2013-03-07 17:31:27

+0

是的,只是修復它 – OregonTrail 2013-03-07 17:32:09