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.
When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str[] is an auto variable then the string is stored in stack segment, if it's a global or static variable then stored in data segment, etc.
Allocating Strings DynamicallyEdit In duplicating a string, s, for example we would need to find the length of that string: int len = strlen(s); And then allocate the same amount of space plus one for the terminator and create a variable that points to that area in memory: char *s2 = malloc((len + 1) * sizeof(char));
How is a string stored in C? The strings declared as character arrays are stored like other arrays in C. For example, if str[] is an auto variable, the string is stored in the stack segment; if it's a global or static variable, then stored in the data segment.
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?
There are several data structures that allow you to grow dynamically. As the 2 previous replies suggest, you can use an array of pointers, a linked-list etc.
It all depends on the requirements of your implementation:
etc. I suggest reading a bit about data structures and deciding what suits you best. They can all be implemented in C.
Look at this Wikipedia article (go to the 'Examples' section for a list of options, if you want to skip the theory)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With