HOWTO: Initilize Large Character ArraysID: Q38728
|
A common problem in C programming is initializing a large character array. There are several ways of doing this, as well as several potential problems.
char a[] = "a"
"b";
is the same as:
char a[] = "ab";
This allows placing large literal initializers into the code as shown
below. This method runs into the compiler limit.
char stuff[] =
"xxx...xxx"
...
"xxx...xxx";
(The ANSI standard states that strings separated only by white space
are automatically concatenated.)
char stuff [] =
{ 'a', ...
...
... 'z' };
However, such an initializer is tedious to type. If using this method,
write a program that will read a data file and output the proper
initializer.
char stuff[][10] = {
"0123456789",
...
"0123456789" };
The value 10 is not important EXCEPT that it must match the actual
length of the string constants. If any of the constants are shorter
than the length specified, the end of that row will be padded out with
zero bytes. If any are longer, the extra characters will be thrown
away. This results in a two dimensional array. Another pointer can be
used to access the following in almost any method desired:
char *stuffptr = (char *) stuff;
This method seems to be the most convenient. The big problem with
using a pointer to try and address the array as a single dimensional
array is that the extra null characters make counting difficult,
particularly if all the initializer strings are not the same length.
Thus stuffptr[97] may not access the element you expect unless you
count very carefully.
stuff db "abcdefghijkl"
db "morestuff"
...
db "laststuff"
In C, access the array with the following:
extern char stuff[]; /* char * stuff; will NOT work */
Additional query words:
Keywords : kbLangC kbVC100 kbVC150 kbVC151 kbVC152 kbVC200 kbVC210 kbVC400 kbVC500 kbVC600
Version : MS-DOS:6.0,6.00a,6.00ax,7.0; WINDOWS:1.0,1.5,1.51,1.52; WINDOWS NT:1.0,2.0,2.1,4.0,5.0
Platform : MS-DOS NT WINDOWS
Issue type : kbhowto
Last Reviewed: July 5, 1999