2013-03-07 3 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 인 클래스 멤버에 태그를 지정합니까? – m0skit0

+0

컴파일하고 실행하여 와트를 확인 했습니까? 대답은 –

답변

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 문으로 printof sizeof (struct PodTag)를 사용하지 않아야합니까 ?? –

+0

예, 방금 고쳤습니다. – OregonTrail