I want to store lines of strings dynamically using C language.
for e.g
sadasdasda5245sdf
fadfa6456
fasdf90-70=790
the number of such lines and the length of each line can be anything.Is there any way to store the whole thing dynamically.
I want to store lines of strings dynamically using C language.
for e.g
sadasdasda5245sdf
fadfa6456
fasdf90-70=790
the number of such lines and the length of each line can be anything.Is there any way to store the whole thing dynamically.
There are several data structures that allow you to add items dynamically, without having to know in advance what the maximum number of elements required are. There are linked lists, binary search trees, balanced trees, tries, heaps and many more.
Similarly, there are lots of ways of dynamically allocating strings of different lengths.
The easiest way would probably be to use a simple linked list:
typedef struct _node {
struct _node *next;
char *value;
} node_t;
You keep track of the head, the first item in the list, and each next field points to the next node in the list. For example, to traverse the list, you would write something like this:
currentNode = head;
while(currentNode != NULL) {
/* do something with currentNode->value */
currentNode = currentNode->next;
}
Without knowing what you want to do, specifically, I can't really offer any better suggestions.
What operations do you want to carry out on your data structure often? Are you going to simply be iterating through the strings, searching for strings, adding and removing strings?
Run, don't walk, to the Princeton web site and get
Dave Hanson's C Interfaces and Implementations. The data structure called Seq_T
is perfect for building up a list of lines dynamically. Dave doesn't provide a buffering reader, but you can read lines into a finite buffer, convert the result using Text_put
, and if a line is too big for one buffer, join the results using Text_cat
. The CII code manages all the dynamic growth for you.
If you know at some initialization time the number of strings and will not need to allocate for more, you could just use a:
char **myStrings = (char **)malloc(numStrings*sizeof(*myStrings);
and then allocation for each string:
for(int i=0; i<numStrings; i++)
myStrings[i] = (char *)malloc(stringLength[i] + 1);
You could still allocate more dynamically if needed, though.
If you need to dynamically reallocate the array of strings:
myStrings = (char **)realloc(myStrings, numStringsNew*sizeof(myStrings));
or if a particular string needs to change its length, just realloc that particular string:
myStrings[the_one_to_realloc] = (char *)realloc(myStrings[the_one_to_realloc], stringLengthNew + 1);
There is little reason to reinvent the wheel, unlike what some answers suggest.
Do not develop your own library, while there are several free software libraries which implement such abstractions. One example, among others, is glib which has many types such as dynamically growing strings and dynamically growing lists.