Created
February 21, 2017 18:24
-
-
Save scizzorz/f1b42addc7c42f60af3d1e4aa5b471e3 to your computer and use it in GitHub Desktop.
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 <stdio.h> | |
#include <stdlib.h> | |
typedef struct item { | |
int id; | |
} item; | |
typedef struct container { | |
int cur, max; | |
item items[0]; | |
} container; | |
typedef struct bad_container { | |
int cur, max; | |
} bad_container; | |
container *new_container(int N) { | |
container *x = malloc(sizeof(container) + sizeof(item) * N); | |
x->cur = 0; | |
x->max = N; | |
for(int i=0; i<N; i++) { | |
x->items[i].id = i; | |
} | |
return x; | |
} | |
bad_container *new_bad_container(int N) { | |
bad_container *x = malloc(sizeof(bad_container) + sizeof(item) * N); | |
x->cur = 0; | |
x->max = N; | |
item *items = (item *)(x + 1); | |
for(int i=0; i<N; i++) { | |
items[i].id = i; | |
} | |
return x; | |
} | |
int main() { | |
container *x = new_container(10); | |
bad_container *y = new_bad_container(10); | |
item *y_items = (item *)(y + 1); | |
for(int i=0; i<10; i++) { | |
printf("x->items[%d].id = %d\n", i, x->items[i].id); | |
printf("y_items[%d].id = %d\n", i, y_items[i].id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment