Here I have a pointer to the first element and int to hold the number of elements. How do I add in malloc and calloc for memory allocation?
struct vector_new
{
char *start;
int count;
}
Here I have a pointer to the first element and int to hold the number of elements. How do I add in malloc and calloc for memory allocation?
struct vector_new
{
char *start;
int count;
}
vector = malloc(sizeof(struct vector_new))
vector->start = malloc(size);
vector->count = size;
I'm not sure exactly what you are asking for.
BTW, std::vector has a "used" size and a "allocated" size, a semantic which you do not reproduce here.
I also agree that you are unlikely to write this faster than std::vector. There may be reasons to use C instead of C++, but that isn't one of them.
You are looking for a "dynamic array" implementation.
You keep track of both how many objects are currently in the array and how much space is allocated for it. When you need more space you call realloc
and ask for current_size * factor
where factor
is greater than one. Typical values for factor
are between 1.4 and 2.
It can be shown that the amortized cost of appending n
items to the array is O(n).
Note that this is not efficient if you want to insert stuff into the middle. That's a different critter.
I'm not sure I understand your question, but is this what you are looking for:
vector_new vec;
vec.count = 10;
vec.start = malloc(vec.count);