Skip to content

Instantly share code, notes, and snippets.

@avar
Created December 6, 2018 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avar/e208ed6e07df85b7b9cf5d7c33b899f3 to your computer and use it in GitHub Desktop.
Save avar/e208ed6e07df85b7b9cf5d7c33b899f3 to your computer and use it in GitHub Desktop.
Shows that (in practice, not standard) structs are just a fancy linear container of their types (assuming alignment works out) in memory
#include <stdio.h>
#include <stdlib.h>
struct coord {
int x;
int y;
int z;
};
int main(void)
{
struct coord *v = malloc(sizeof(struct coord) * 2);
int *ptr = (int*)v;
for (int i = 0; i < 6; i++)
ptr[i] = 100 + i;
for (int i = 0; i < 2; i++)
printf("v[%d] = {%d, %d, %d}\n", i, v[i].x, v[i].y, v[i].z);
return 0;
}
@avar
Copy link
Author

avar commented Dec 6, 2018

$ gcc -Wall -Wextra -Wpedantic -o test test.c; ./test
v[0] = {100, 101, 102}
v[1] = {103, 104, 105}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment