Skip to content

Instantly share code, notes, and snippets.

@scolton99
Last active February 16, 2021 20:41
Show Gist options
  • Save scolton99/39bf68bfac109930c04b949045856917 to your computer and use it in GitHub Desktop.
Save scolton99/39bf68bfac109930c04b949045856917 to your computer and use it in GitHub Desktop.
C Union Demo
#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;
}
@scolton99
Copy link
Author

Both printf statements should output the same string.

@scolton99
Copy link
Author

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