C: Creating a collection of structures/ creating an list of integers
I was wondering if you can create a list of integers.
As you know most of the other languages you can have a infinite list of numbers. But i don't know if you can do that with C.
in C you can do
int integers[20]; But I do not want to declare a size for it, instead I want a list that keeps on going forever.
and in addition, I have a structure
typedef struct someStruct
{
char data;
chat data2;
}STRUCT_REC,*SR;
in order to make a list of structures we just do STRUC开发者_如何学运维T_REC list; right?
You've got two options:
Use a dynamically allocated array. You allocate the amount of space you need using malloc(). You can then allocate more space using realloc(). The downsides to this approach are that you generally will be allocating more space than you need, and when you reallocate space, the program may have to move all of your items to a new location in memory which can be costly.
Use a linked list. Linked lists allow you to dynamically allocate space for a single item at any time and add it to the end of the list. To do this, a linked list is composed of nodes, each of which holds one item of data and one pointer to the next node. The downside to this approach is that you lose fast random access (i.e. if you want item #100, you have to look at items 1-99 first), and you have additional space overhead from the additional pointers.
http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/
You can use realloc to increase the amount of memory alloted. Also, the example on that page is probably what you want to study. It is close to what you are looking for.
You need to look at malloc
and friends (calloc
, realloc
, free
).
The way to use it is the same no matter what type you use.
Here's an very simple example with doubles:
#include <stdlib.h>
int main(void) {
double *arr;
arr = malloc(1 * sizeof *arr); /* size for 1 element */
if (arr) {
double *tmp;
tmp = realloc(arr, 100 * sizeof *tmp); /* attempt to resize for 100 elements */
if (tmp) {
arr = tmp; /* resize 'worked' */
} else {
/* not enough memory */
free(arr);
exit(EXIT_FAILURE);
}
/* use arr */
free(arr);
}
return 0;
}
Do you need a list or do you need to write the code for a list? If the former, I suggest you not reinvent the wheel but use an existing tested library such as glib.
The answers to this question may be of interest to you:
A data structure supporting O(1) random access and worst-case O(1) append?
精彩评论