Skip to content

Instantly share code, notes, and snippets.

@sirjofri
Created July 15, 2018 12:58
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 sirjofri/19fe5e30ceed553b6b1604de349c8a10 to your computer and use it in GitHub Desktop.
Save sirjofri/19fe5e30ceed553b6b1604de349c8a10 to your computer and use it in GitHub Desktop.
dynamic buffer/array in C in 30 lines
#include <string.h>
#include <stdlib.h>
#define buffer(type) \
typedef struct type##_buf { \
size_t size; \
type *buffer; \
} type##_buf; \
void _resize_buffer_##type(struct type##_buf *buf) { \
type *newbuf = malloc((buf->size++)*sizeof(type)); \
memcpy((void *)newbuf, (void *)buf->buffer, buf->size * sizeof(type)); \
free(buf->buffer); \
buf->buffer = newbuf; \
} \
void append_##type(struct type##_buf *buf, type element) { \
buf->buffer[buf->size - 1] = element; \
_resize_buffer_##type(buf); \
} \
type##_buf *new_##type##_buf() { \
type##_buf *buffer = malloc(sizeof(type##_buf)); \
buffer->size = 1; \
buffer->buffer = malloc(sizeof(type)); \
return buffer; \
} \
void remove_##type(struct type##_buf *buf, size_t index) { \
type *newbuf = malloc((buf->size--)*sizeof(type)); \
memcpy((void *)newbuf, (void *)buf->buffer, index*sizeof(type)); \
memcpy((void *)(newbuf + index), (void *)(buf->buffer + index + 1), buf->size-index+sizeof(type)); \
buf->buffer = newbuf; \
}
#include <stdio.h>
#include "buffer.h"
buffer(int);
buffer(char);
int
main(int argc, char **argv)
{
int_buf *intbuf = new_int_buf();
char_buf *charbuf = new_char_buf();
append_int(intbuf, 10);
append_int(intbuf, 20);
append_int(intbuf, 30);
append_int(intbuf, 40);
append_int(intbuf, 50);
append_int(intbuf, 60);
append_char(charbuf, 'a');
append_char(charbuf, 'b');
append_char(charbuf, 'c');
printf("char Size: %d\n", charbuf->size);
printf("char Content: %c, %c, %c\n",
charbuf->buffer[0],
charbuf->buffer[1],
charbuf->buffer[2]);
printf(" int Size: %d\n", intbuf->size);
printf(" int Content: %d, %d, %d, %d, %d, %d\n",
intbuf->buffer[0],
intbuf->buffer[1],
intbuf->buffer[2],
intbuf->buffer[3],
intbuf->buffer[4],
intbuf->buffer[5]);
remove_int(intbuf, 3);
printf(" int Size: %d\n", intbuf->size);
printf(" int Content: %d, %d, %d, %d, %d\n",
intbuf->buffer[0],
intbuf->buffer[1],
intbuf->buffer[2],
intbuf->buffer[3],
intbuf->buffer[4]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment