Created
July 25, 2023 17:14
-
-
Save Frityet/0e2215f9f67772783ed97b9a24f96513 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 <stddef.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
struct Array { | |
size_t type_size, element_count; | |
uint8_t data[]; | |
}; | |
static void *create_array(size_t type_size, size_t element_count) { | |
struct Array *array = calloc(1, sizeof(struct Array) + type_size * element_count); | |
array->type_size = type_size; | |
array->element_count = element_count; | |
return array->data; | |
} | |
static void free_array(void *array) | |
{ free(((struct Array *)array) - 1); } | |
static size_t type_size(void *array) | |
{ return ((struct Array *)array - 1)->type_size; } | |
static size_t element_count(void *array) | |
{ return ((struct Array *)array - 1)->element_count; } | |
typeof(int[2]) *pair(int i, int x) | |
{ | |
int (*array)[2] = create_array(sizeof(int), 2); | |
(*array)[0] = i; | |
(*array)[1] = x; | |
return array; | |
} | |
int main() | |
{ | |
int (*array)[3] = create_array(sizeof(int), 3); | |
(*array)[0] = 1; | |
(*array)[1] = 2; | |
(*array)[2] = 3; | |
assert(type_size(array) == sizeof(int)); | |
assert(element_count(array) == 3); | |
int *headptr = (int *)&array[0]; | |
int *plainify = &(*array)[0]; | |
assert(headptr == plainify); | |
free_array(array); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment