P
P
pshevnin2021-11-27 01:09:22
C++ / C#
pshevnin, 2021-11-27 01:09:22

How to insert an element at a specific place in a vector in C?

Good afternoon. There is a dynamic array implemented using vector in C.

int vector_push_back(vector_t *v, const void *item) {
    if (!v || !item) {
        return 0;
    }

    if (v->count == v->capacity) {
        if (!vector_realloc(v, v->capacity * VECTOR_SIZE_MULT)) {
            return 0;
        }
    }

    memcpy((void *)((char *)v->data + (v->count * v->item_size)), item, v->item_size);
    v->count++;

    return 1;
}
This is the function of adding a new element. How can I make it so that I can insert new elements at a specific location in an array using an index? Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-11-27
@pshevnin

First, using memmove, you need to shift the elements from i to count-1 to positions i+1...count. Then slightly change memcopy to write the new element to position i, not count.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question