5 ms·
A much more simple alternative way of doing this is to use stretchy buffers. Here's an example of a dynamic array in C in about 20 lines: http://nothings.org/s
by lasagnaphil 6y ago
A much more simple alternative way of doing this is to use stretchy buffers.
Here's an example of a dynamic array in C in about 20 lines: http://nothings.org/stb/stretchy_buffer.txt http://nothings.org/stb/stretchy_buffer.txt
And here's a friendly explanation of how this technique works: https://ourmachinery.com/post/minimalist-container-library-in-c-part-1/ https://ourmachinery.com/post/minimalist-container-library-i...
- addaon 6y agoBut this entirely misses the "type safe" part...
- tom_mellior 6y agoMy understanding is that if you declare some_concrete_type *p; some_other_type x; then, for example, sbpush(p, x); will result in a type error as expected, since its core expands to: p[some_index] = x; So this is kind of type safe. There is an assumption that ((int *) <guaranteed aligned pointer>) + 2 will still be correctly aligned for any type. That's a pretty fair assumption on modern hardware, except maybe for SIMD types.
- lifthrasiir 6y agoSay no to masqueraded pointers! They require a specific coding convention that can't be checked by compilers since it is effectively a linear (or affine if you are pedantic) type. Put in the other way, masqueraded pointers make many otherwise non-destructive operations destructive without you realizing.
- Aanok 6y ago> assert(p); > if (p) { Do you want me to have an embolism?
- tom_mellior 6y agoHaha. I was amused/bewildered by: void *p = realloc(...) // ... cast every other occurrence of p to (int *) ... The concept may be interesting, but this particular implementation is needlessly horrible.
- Aanok 6y agoThat's actually correct C pointer arithmetic. When you increment a pointer, it moves ahead by the sizeof the underlying concrete type. If the pointer is to void, there is no underlying type and in fact void pointer arithmetic is disallowed by the standard. GCC lets you do it with an extention: https://gcc.gnu.org/onlinedocs/gcc-4.8.0/gcc/Pointer-Arith.html https://gcc.gnu.org/onlinedocs/gcc-4.8.0/gcc/Pointer-Arith.h... So in this case, since the headers for the arrays are made up of two int's it's the right thing to do to move around by sizeof(int) memory address units. You do this with a cast before the arithmetic.
- tom_mellior 6y agoMy point was, why not declare the pointer as int * directly since that the only type it's used as?
- efficax 6y agoto be fair, if assert is removed in release code, you still have some protection with the `if`