Last active
February 16, 2021 20:41
-
-
Save scolton99/39bf68bfac109930c04b949045856917 to your computer and use it in GitHub Desktop.
C Union Demo
This file contains hidden or 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 <stdio.h> | |
typedef union U1 { | |
int a[2]; | |
char c; | |
short s; | |
} U1; | |
int main() { | |
long long tmp; | |
char* mem = (char*)&tmp; | |
mem[0] = 0xFF; | |
mem[1] = 0xEF; | |
mem[2] = 0xDF; | |
mem[3] = 0xCF; | |
mem[4] = 0xBF; | |
mem[5] = 0xAF; | |
mem[6] = 0x9F; | |
mem[7] = 0x8F; | |
void* ptr = (void*)mem; | |
int* a = (int*)ptr; | |
int* b = (int*)(ptr + 4); | |
char* c = (char*)ptr; | |
short* d = (short*)ptr; | |
printf("0x%X, 0x%X, 0x%hhX, 0x%hX\n", *a, *b, *c, *d); | |
U1* u = (U1*)ptr; | |
printf("0x%X, 0x%X, 0x%hhX, 0x%hX\n", u->a[0], u->a[1], u->c, u->s); | |
return 0; | |
} |
This example relies on some undefined behavior; pay no mind to that.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Both
printf
statements should output the same string.