Need help with pointer to array[][]

chris at mimsy.UUCP chris at mimsy.UUCP
Tue Feb 10 07:28:12 AEST 1987


In article <1911 at utah-gr.UUCP> thomas%spline.uucp at utah-gr.UUCP
(Spencer W. Thomas) writes:
>If you want to dynamically allocate an array exactly the same shape you
>had, you can do this:
>	char (*fnames)[16][32];
> 
>	fnames = (char (*)[16][32])malloc(16*32*sizeof(char));
>	GetFileNames(*fnames);
>	for (i = 0; i < 16; i++)
>	    printf("%s\n", (*fnames)[i]);
>
>(This code compiles and lints on my HPUX system.  The sizeof(char) is
>just sheer paranioa.)

(You could use `sizeof (char [16][32])', or `sizeof (*fnames)'.)

This works, but considering that the original code was (presumably)

	char fnames[16][32];

	GetFileNames(fnames);
	for (i = 0; i < 16; i++)
		printf("%s\n", fnames[i]);

requires changing any occurrences of `fnames' to `(*fnames)'.  The
only advantage of the new code is that the storage for the names
can be allocated dynamically.  A more likely replacement is

	char (*fnames)[32];

	fnames = (char (*)[32]) malloc(16 * sizeof (char [32]));
	GetFileNames(fnames);
	for (i = 0; i < 16; i++)
		printf("%s\n", fnames[i]);

---which requires only the new declaration and allocation.

Of course, proper paranoia also includes checking the return
value from malloc():

	if ((fnames = (char (*)[32]) malloc(16 * sizeof (char [32))) == NULL)
		...		/* handle out of memory error */

Another annoying nit is that malloc() takes an unsigned argument,
while sizeof has type `size_t', which is not necessarily unsigned
(it is signed in 4BSD), requiring yet more casts.  (I would rather
have an unsigned `size_t'.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690)
UUCP:	seismo!mimsy!chris	ARPA/CSNet:	chris at mimsy.umd.edu



More information about the Comp.lang.c mailing list