C Vector / ArrayList / LinkedList

I am making a small C program and I need some kind of vector / ArrayList / LinkedList, but I work with C. Any idea on how I can do such things in C?

I want to save structures and then add / remove some.

+3
source share
4 answers

For scalable arrays you can use malloc()and realloc(). They allow you to reserve (s malloc()) and resize (s realloc()) a certain amount of space in the heap. They are used in this way:

int* a = malloc(10 * sizeof(int));

if(a == NULL) {}     // malloc() was unable to allocate the memory, handle the
                     // error and DO NOT use this pointer anymore

// now you can treat a as a normal array of 10 ints:
a[4] = 51;

// suppose 10 ints aren't no more enough:
a = realloc(a, 20 * sizeof(int));

if(a == NULL) {}     // same thing as before

// here you have 20 ints, the previous 10 are still there
a[18] = a[4]

// don't forget to free the memory when you have finished:
free(a);

Just replace 'int' with your structure type .;)

+3
source

. . Glib, , , LibH.

+5

@Conrad Meyer. Glib . Glib . . .

, . Valgrind :

==20350== HEAP SUMMARY:
==20350==     in use at exit: 4,632 bytes in 12 blocks
==20350==   total heap usage: 12 allocs, 0 frees, 4,632 bytes allocated
==20350== 
==20350== LEAK SUMMARY:
==20350==    definitely lost: 0 bytes in 0 blocks
==20350==    indirectly lost: 0 bytes in 0 blocks
==20350==      possibly lost: 992 bytes in 4 blocks
==20350==    still reachable: 3,640 bytes in 8 blocks
==20350==         suppressed: 0 bytes in 0 blocks

, :

#include <stdio.h>
#include <glib.h>

int main(int argc, char** argv) {
    GList* list = NULL;
    list = g_list_append(list, "Hello world!");
    printf("The first item is '%s'\n", (char *)g_list_first(list)->data);
    g_list_free(list);
    return 0;
}

Valgrind:

==20310== HEAP SUMMARY:
==20310==     in use at exit: 4,632 bytes in 12 blocks
==20310==   total heap usage: 12 allocs, 0 frees, 4,632 bytes allocated
==20310== 
==20310== LEAK SUMMARY:
==20310==    definitely lost: 0 bytes in 0 blocks
==20310==    indirectly lost: 0 bytes in 0 blocks
==20310==      possibly lost: 0 bytes in 0 blocks
==20310==    still reachable: 4,632 bytes in 12 blocks
==20310==         suppressed: 0 bytes in 0 blocks

, still reachable .

+2

C - ( , ++ Java), :

  • , - / ( ).

, , , . , , , , :

See the Wikipedia page for more information on compromising between two types of data structures.

+1
source

Source: https://habr.com/ru/post/1785654/


All Articles