Bounded Malloc Array

Run Settings
LanguageC++
Language Version
Run Command
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <assert.h> #define CONCAT_(a,b) a##b #define CONCAT(a,b) CONCAT_(a,b) #define VAR_TYPE float #define VAR_NAME f32 #include "bound_array.cpp" #define VAR_TYPE int64_t #define VAR_NAME s64 #include "bound_array.cpp" int main() { Array_f32 eple = Array_f32_init(32); eple[31] = 91; printf("eple.size = %lu\neple[31] = %f\n", eple.size, eple[31]); Array_s64 pera = Array_s64_init(54); pera[24] = 3771; printf("pera.size = %lu\npera[24] = %li\n", pera.size, pera[24]); return 0; }
#ifndef VAR_TYPE #error "VAR_TYPE is not defined." #endif #ifndef VAR_NAME #error "VAR_NAME is not defined." #endif #define ARRAY_TYPE CONCAT(Array_, VAR_NAME) struct ARRAY_TYPE{ uint64_t size; VAR_TYPE *element; VAR_TYPE &operator [](uint64_t index) { assert(index < size); return element[index]; } }; static ARRAY_TYPE CONCAT(ARRAY_TYPE, _init) (uint64_t size_in) { ARRAY_TYPE result; result.element = (VAR_TYPE *)malloc(size_in * sizeof(VAR_TYPE)); assert(result.element); result.size = size_in; return result; } #undef ARRAY_TYPE #undef VAR_TYPE #undef VAR_NAME
Editor Settings
Theme
Key bindings
Full width
Lines