Created
September 7, 2015 12:56
-
-
Save k0f1sh/7fac7792c79d716ed126 to your computer and use it in GitHub Desktop.
offsetofを試した
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stddef.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
struct address | |
{ | |
char name[50]; | |
char street[50]; | |
int phone; | |
}; | |
int main() | |
{ | |
struct address *hoge = malloc(sizeof(struct address)); | |
strcpy(hoge->name, "taro"); | |
strcpy(hoge->street, "hokkaido"); | |
hoge->phone = 123456; | |
printf("name = %s\n", hoge->name); | |
printf("street = %s\n", hoge->street); | |
printf("phone = %d\n", hoge->phone); | |
printf("-------\n"); | |
printf("hoge addr = %p\n", hoge); | |
printf("name addr = %p\n", hoge->name); | |
printf("street addr = %p\n", hoge->street); | |
printf("phone adrr = %p\n", &hoge->phone); | |
printf("-------\n"); | |
size_t offset = offsetof(struct address, phone); | |
printf("phone offset = %d\n", offset); | |
printf("phone offset = 0x%x\n", offset); | |
printf("\n\n"); | |
int *phone_addr = &hoge->phone; | |
struct address *t = (struct address *)((char *)phone_addr - offset); | |
printf("struct address *t = (struct address *)((char *)phone_addr - offset);\n"); | |
printf("result: t = %p\n", t); | |
printf("t->name = %s\n", t->name); | |
return(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment