Last active
July 10, 2023 17:59
-
-
Save okyanusoz/787160bdca1e2a4381e77aaa71e7613e to your computer and use it in GitHub Desktop.
Basic vectors/arrays in C
This file contains hidden or 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 <stdlib.h> | |
#include <memory.h> | |
struct Vector { | |
int size; | |
uint8_t* offset; | |
}; | |
void vector_resize(struct Vector* vec, int newsize) { | |
vec->offset = realloc(vec->offset, newsize); | |
vec->size = newsize; | |
} | |
struct Vector vector_init(uint8_t* init, int init_size) { | |
struct Vector vec; | |
vec.size = 0; | |
if(init != NULL) { | |
vector_resize(&vec, init_size); | |
memcpy(vec.offset, init, init_size); | |
} | |
return vec; | |
} | |
void vector_set(struct Vector* vec, int idx, uint8_t value) { | |
if(idx > vec->size-1) { | |
vector_resize(vec, idx+1); | |
} | |
vec->offset[idx] = value; | |
} | |
void vector_append(struct Vector* vec, uint8_t value) { | |
vector_set(vec, vec->size, value); | |
} | |
int vector_read(struct Vector* vec, int idx) { | |
return vec->offset[idx]; | |
} | |
void vector_destroy(struct Vector* vec) { | |
if(vec->size == 0) return; | |
free(vec->offset); | |
vec->size = 0; | |
} | |
int main() { | |
uint8_t init[] = {1,2,3}; | |
struct Vector vec = vector_init(init, 3); | |
vector_append(&vec, 30); | |
vector_append(&vec, 3); | |
printf("Vector size: %d\n", vec.size); | |
for(int i=0; i < vec.size; i++) { | |
uint8_t val = vector_read(&vec, i); | |
printf("Index %d: %d\n", i, val); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment