Reputation: 14296
I have a struct PACKET which contains two int fields. How would I declare a dynamic array of PACKETs? I will be adding to the array an unknown number of times in the main...that is why I need it to be dynamically sized.
Upvotes: 1
Views: 1761
Reputation: 473
Encapsulate your dynamic array implementation with malloc/realloc in a .h/.c file pair for easier use.
static int length = 0;
PACKET *dynamic_array_put(PACKET *list, const PACKET new) {
PACKET *ret_val = NULL;
ret_val = realloc(list, sizeof(PACKET) * (length + 1));
if (ret_val == NULL) {
/* Not enough memory */
return NULL;
}
memmove(list + length, &new, sizeof(PACKET));
length++;
return ret_val;
}
PACKET *dynamic_array_get(PACKET *list, int index) {
PACKET *p = NULL;
p = malloc(sizeof(PACKET));
if (p == NULL) {
/* Not enough memory */
return NULL;
}
memmove(p, list + index, sizeof(PACKET));
return p;
}
PACKET *dynamic_array_remove(PACKET *list, int index) {
PACKET *ret_val = NULL;
PACKET tmp;
memmove(&tmp, list + index, sizeof(PACKET));
memmove(list + index, list + index + 1,
sizeof(PACKET) * (list - index - 1));
ret_val = realloc(list, sizeof(PACKET) * (list - 1));
if (ret_val == NULL) {
/* Not enough memory, restore! */
memmove(list + index + 1, list + index,
sizeof(PACKET) * (list - index - 1));
memmove(list + index, &tmp, sizeof(PACKET));
return NULL;
}
length--;
return ret_val;
}
If memory space is no issue, you can do the memory allocation in blocks, instead of at every addition of PACKETs and speed up the average addition.
Upvotes: 1
Reputation: 41627
Depending on the environment you are using, you have these options:
malloc
and realloc
GArray
or GList
data type from GNOMEstd::vector<PACKET>
ArrayList
The standard C is very limited in its runtime library, but many people have already extended that standard library to be useful. You should not need to write that code yourself, unless you are in an exotic environment.
Upvotes: 2
Reputation: 20044
Make yourself familiar with malloc
and realloc
- here is some kind of example / small tutorial:
http://fydo.net/gamedev/dynamic-arrays
Here is a more elaborate explanation:
http://www.cse.unt.edu/~donr/courses/4410/dynamicArrays/dynamicArrays.html
When dealing with realloc
, you will most likely have to manage the actual size of the array and the reserved capacity of the array as two different values. That is for performance reasons, otherwise, you would have to call realloc
every time you add one element to it, which can get extremely slow even for arrays containing just a few hundred elements.
Upvotes: 1