Arraylist in C not working

前端 未结 4 732
旧时难觅i
旧时难觅i 2020-12-30 15:54

I am currently writing a program to implement an arraylist (or dynamic array) in C. Hmm... I think I have 70 - 80% done with it, however, I found a serious problem with my c

4条回答
  •  悲哀的现实
    2020-12-30 16:09

    As others have noted, the problem is in the arraylist_add() function, which needs to dynamically allocate memory. This problem is actually perfectly suited for realloc(), which will expand the dynamically allocated array (meaning you don't have to do the copying loop):

    void arraylist_add(struct arraylist *list, value_type value) {
      int size = arraylist_get_size(*list);
      value_type *new_data;
    
      new_data = realloc(list->data, (size + 1) * sizeof new_data[0]);
    
      if (new_data)
      {
          new_data[size] = value;
          arraylist_set_data_collection(list, new_data);
          ++list->size;
      }
    }
    

    This will even work for the first allocation, since realloc() works like malloc() if you pass it a NULL.

    PS:

    To make the implementation more efficient, you shouldn't expand the array by one entry each time - instead, keep track of the number of allocated blocks separately from the number of entries.

提交回复
热议问题