
How access alloc'ed string as array?
Quote:
>>>I would like to allocate a block of memory from the heap and then
>>>treat it as a two-dimensional array. I know it's easy, but I just
>>>can't seem to get the syntax right. My compiler manual offers no
>>>help. Thanks
>I think that the following code might be along the lines of what you
>are looking for...
>#include <stdio.h>
>#include <stdlib.h>
>#include <string.h>
>int main()
>{
> char **array;
> int i;
> char string[] = "hi\n";
> array = (char **) malloc(first_dim_size * sizeof(char *));
There is no need to cast the return of malloc and unnecessary can, in
some cases hide errors. I guess we're assuming that first_dim_size was
defined and initialized somewhere.
You should test the return of any allocation for failure:
if( array == NULL)
{
fprintf( stderr, "Allocation failure.\n");
exit( EXIT_FAILURE);
}
Quote:
> /* the above creates the space needed for the first dimension */
> /* of the desired array. */
> for (i = 0; i < first_dim_size; i++)
> *array = (char *) malloc(sizeof(char *));
?? I think you intended something more like:
array[i] = malloc(sizeof(string) + 1);
/* same allocation test as above on each iteration */
The c.l.c faq discusses several methods of allocating two dimensional
arrays. You can ftp it from rtfm.mit.edu /pub/usenet/comp.lang.c.
--
John R Buchan -:|:- Looking for that elusive FAQ? ftp to: