-1

I need to insert into an array which size is unknown an unknown number of elements , the array needs to grow each time i insert an element one by one, until end of data . how can i do such thing ? can someone give me an example of how to do it ? Thank you.

AVITAL
  • 11
  • 2
  • 1
    I find it near-impossible to believe that [`[c] dynamic array`](https://stackoverflow.com/search?q=%5Bc%5B%5D+dynamic+array) in any search box on this very site yields *nothing* of value. I see *thousands* of hits. – WhozCraig Aug 10 '22 at 08:22
  • 1
    Does this answer your question? [C dynamically growing array](https://stackoverflow.com/questions/3536153/c-dynamically-growing-array) – Michael M. Aug 12 '22 at 03:39

1 Answers1

0

Arrays in C don't know their size. And inserting a value needs to copy every element from this point to the end of the array (its size). This is impossible in c. But you could implement an array or a list youself.

typedef struct List {
    void** data;
    int capacity;
    int size;
} List;

void init_list(List* l) {
    l->data = NULL;
    l->capacity = 0;
    l->size = 0;
}

void increase_capacity(List* l) {
    l->capacity += 8;
    l->data = realloc(l->data, sizeof(void*) * l->capacity);
}

void insert(List* l, void* item, int index) {
    if (l->capacity <= l->size) {
        increase_capacity(l);
    }
    // or just memmove(l->data + index + 1, l->data + index, l->size - index);
    for (int i = list->size; i > index; i--) {
         l->data[i] = l->data[i-1];
    }
    l->data[index] = item;
    l->size++;
}

Add other useful functions like add remove and so on.

If you are unsure what functions I use do, read their man pages (for example "man realloc" in the command line or google).

Also, do a C course to know how arrays behave and why other languages know their size and C doesn't.

Spoiler: they just use a struct to remember it.

Tenobaal
  • 637
  • 1
  • 16