Created
July 15, 2018 12:58
-
-
Save sirjofri/19fe5e30ceed553b6b1604de349c8a10 to your computer and use it in GitHub Desktop.
dynamic buffer/array in C in 30 lines
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 <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; \ | |
} |
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 "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