What’s the standard or common data structure for a list of objects in C?

In C, what’s the standard or common data structure for a list of objects?

In C, one common way to store a list/collection of objects of the same type is to use one-dimensional arrays.

In C, an array is a collection of data objects of the same type. An array is in a contiguous memory area. The lowest address of the memory area corresponds to the first element in the array and all other elements follow it one by one.

Arrays can be statically allocated or dynamically allocated:

// statically allocated
// declare a static array a1 of 100 ints
int a1[100];

// dynamically allocated on the heap
// allocate a dynamical array a1 of 100 ints
int a2_len = 100;
int *a2 = (int *)malloc(sizeof(int) * a2_len);

Element access time in an array has O(1) complexity. Memory management like increasing the size of an array should be done grammatically. Some library functions may help though. For example, void *realloc(void *ptr, size_t size) changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes, and returns a pointer to the newly allocated memory which may be different from ptr.

One example to sum the a1 and a2 together into a2:

int i = 0;
for (i = 0; i < 100; ++i) {
  a2[i] += a1[i];
Leave a Reply

Your email address will not be published. Required fields are marked *