Need help with pointer to array[][]

thomas at spline.UUCP thomas at spline.UUCP
Mon Feb 9 06:16:41 AEST 1987


In article <132 at batcomputer.tn.cornell.edu> hsgj at batcomputer.tn.cornell.edu (Dan Green) writes:
>However, I decided it would be better to malloc this space instead of
>having it static.  How do I declare a pointer to a two-d array?
>My new version is:
>     char *fnames;                    /* What is correct declaration? */
>     fnames = malloc(16*32);
>     GetFileNames(fnames);
>     for (i = 0; i < 16; i++)
>        printf("%s\n",fnames[i*32]);  /* this is wrong, no? */
>

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.)

Another way to do it (which would require modifying the declaration of
the argument to GetFileNames) is the following:

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

...

	GetFileNames(fnames)
	char *fnames[16];

One advantage of this method is that you can easily allocate different
length strings for each element of the "array".

=Spencer   ({ihnp4,decvax}!utah-cs!thomas, thomas at utah-cs.ARPA)



More information about the Comp.lang.c mailing list