Dynamically store string strings using C

I want to store string strings dynamically using C language.

eg,

sadasdasda5245sdf

fadfa6456

fasdf90-70 = 790

the number of such lines and the length of each line can be arbitrary. Is there a way to keep it all dynamic.

+5
source share
6 answers

There are several data structures that allow you to dynamically add items without knowing in advance what the maximum number of items is required. There are linked lists, binary search trees, balanced trees, attempts, heaps, and more.

.

, , :

typedef struct _node {
    struct _node *next;
    char *value;
} node_t;

, , node . , , - :

currentNode = head;
while(currentNode != NULL) {
    /* do something with currentNode->value */
    currentNode = currentNode->next;
}

, , , .

? , , ?

+7

, . 2 , , ..

:

  • ?
  • , ( ) (, )?
  • /?
  • - , ( )?
  • ( )?

... , . C.
( "" , )

+3

, :

char **myStrings = (char **)malloc(numStrings*sizeof(*myStrings);

:

for(int i=0; i<numStrings; i++)
    myStrings[i] = (char *)malloc(stringLength[i] + 1);

, .

:

myStrings = (char **)realloc(myStrings, numStringsNew*sizeof(myStrings));

, :

myStrings[the_one_to_realloc] = (char *)realloc(myStrings[the_one_to_realloc], stringLengthNew + 1);
+3

, , - Princeton Dave Hanson C . , Seq_T, . , , Text_put, , Text_cat. CII .

+2

, , .

, , . , , glib, , .

+2

"m" %s, :

char *variable;
scanf ("%ms", &variable);
/* use variable */
free(variable);

, variable, .

, free .

0

All Articles