Here is the compelte message
Hi,
I need a structure to store a string array in c, for example
Index Content
-------- -----------
0 word1
1 word2
2 word3
3 word4
4 word5
5 word6
There are several approaches with different advantages
and disadvantages. You haven't specified your needs very
precisely, so I'll just sketch out a few methods. Note that
these are NOT equivalent!
/* Fixed-length array of fixed-length words (any
* short words are followed by extra '\0' bytes
* to a total size of six). Array elements are
* modifiable, but no word can grow beyond five
* payload characters.
*/
char words[][5+1] = { "word1", ..., "word6", };
/* Fixed-length array of pointers to words of
* arbitrary length. The pointers can be changed
* to point at different words, but the original
* word data cannot be changes.
*/
char *words[] = { "word1", ..., "word6", };
/* Fixed-length array of pointers to words of
* arbitrary length. Both the pointers and the
* words can be changed, but the original words
* cannot be lengthened in place.
*/
char word1[] = "word1";
...
char word6[] = "word6";
char *words[] = { word1, ..., word6, };
/* Dynamically allocated "array" of fixed-length
* words. Array elements are modifiable, but the
* words themselves cannot be lengthened. The
* typedef is for clarity, and can be eliminated.
*/
typedef char Word[5+1];
Word *words = malloc(N * sizeof *words);
if (words != NULL) {
strcpy (words[0], "word1");
...
strcpy (words[5], "word6");
}
/* Dynamically-allocated "array" of pointers to
* dynamically-allocated words. Everything is
* modifiable, replaceable, extensible, all-
* singing, all-dancing, and carbon-neutral.
*/
char **words = malloc(N * sizeof *words);
if (words != NULL) {
words[0] = malloc(sizeof "word1");
if (words[0] != NULL)
strcpy (words[0], "word1");
...
/* A different way to calculate the size: */
words[5] = malloc(strlen("word6") + 1);
if (words[5] != NULL)
strcpy (words[5], "word6");
}