Roman said:
Hello, All!
I wonder is it possible to define an array containing strings, not
single characters? What I want is array 'table[N]' that will have N
elements, and every element is a strings tailoring with '\0', like that:
table[0] = "string0\0"
table[1] = "string1\0"
...
Unfortunately I have no idea how to do this... May be declare new type
and then declare my array of this new type?
With best regards, Roman Mashak. E-mail: (e-mail address removed)
There are several ways. Remember that in C a string is a
zero-terminated array of char, so one approach is to define a
two-dimensional array of char, with the second dimension long enough to
hold your longest string:
char table[5][10] = {"foo", "ten chars", "blurga", "a string", "S"};
The main drawback to this approach is the potential for lots of wasted
space. If you have 20 strings, 19 of which are 10 characters long
(including terminator), and 1 string that's 50 characters long
(including terminator), then you're wasting 40*19 bytes of storage.
You can elide the second dimension, however, and the array will be
sized for the initializer:
char table[5][] = {"foo", "ten chars", "blurga", "a string", "S"};
So sizeof table[0] == 4, sizeof table[1] == 10, sizeof table[2] == 7,
etc. No wasted space. On the other hand, if you want to change the
contents of each entry, you have to stick with the initial array size
(in other words, table[0] can hold at most 4 characters including the
terminator, whereas table[1] can hold up to 10).
Another approach is to define an array of pointers to char, and set
each element to point to a string literal:
char *table[5] = {"foo", "ten chars", "blurga", "a string", "S"};
However, since each array element points to a string literal, you
cannot modify the contents of each element; you can, however, reassign
the pointer (IOW strcpy(table[0], "bar"); won't work, but table[0] =
"bar" will).
The last way is to define an array of pointers to char, and then use
malloc() (or calloc()) to allocate each string:
char *table[5];
table[0] = malloc(strlen("foo") + 1);
strcpy(table[0], "foo");
table[1] = malloc(strlen("ten chars") + 1);
strcpy(table[1], "ten chars");
etc.
This approach offers the most advantages: no wasted space, you can
modify the contents of each element, and you can resize each element as
necessary using realloc() if you need to write a longer string to that
entry:
char *tmp;
tmp = realloc(table[0], strlen("a much, much longer string than the
original") + 1);
if (tmp)
{
table[0] = tmp;
strcpy(table[0], "a much, much longer string than the original");
}