Mail Archives: djgpp/1999/09/02/12:41:05
On Thu, 2 Sep 1999 04:32:54 -0700, "Dan Gold" <TedMat AT CoastNet DOT com>
wrote:
> Okay this is a stupid newbie question but I never actually learned how it
> was done, mayby better suited for a C programming group but I want to
> allocate an array of strings. I understand how to use strings but not
> create them and not multi-dimensional strings. Could someone please give
> me an example, the array will hold a list of filenames?
>
> // one dimensional
> char * string = (char *)malloc(string_size * sizeof(char));
Either
char * string = new char[string_size]; /* C++ */
delete [] string;
or
char * string = malloc(string_size); /* C */
free(string);
(sizeof (char) is 1 by definition).
You would only need a cast (char*)malloc if you compile the C code
with a C++ compiler which is abomination ;-) Don't mix languages.
> // two dimensional
> ??
This can be interpreted in various ways. You may either want an array
of strings where you allocate the same amount of memory for every
string and in the latter case you may know the common size of the
strings at compile time - or you may not.
Let's step up from the constant case to the variable case
1)
This would be an equivalent to a static array
char a[number][SIZE];
A string would be addressed by a[i].
char (*p)[SIZE] = new char[number][SIZE]; // C++
char (*p)[SIZE] = malloc(number*SIZE); /* C */
'number' may be a variable. SIZE has to be a litteral or #defined
constant or may be something like
const int SIZE=80;
in C++.
The string would be addressed by p[i].
If you don't want to allocate the same size for every string or if the
size is not known at compile time and introduced by a variable, you
have to use an array of pointers to char instead of an array of arrays
of char.
char ** p = new char*[number];
Now for every i from 0 to number-1 you may assign a different size
p[i] = new char[size_for_string_i];
Deletion
for (i=0;i<number;++i) delete [] p[i];
delete [] p;
in C
char ** p = malloc [number * sizeof (char*) ];
or
char ** p = malloc [number * sizeof *p];
p[i] = malloc(size_for_string_i);
Deletion
for (i=0;i<number;++i) free(p[i]);
free(p);
In this case, too, a specific string would be addressed by p[i]
although the underlying "physical" data structure is completely
different. That's one of the miracles of C ;-)
Regards
Horst
- Raw text -