Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!rutgers!mit-eddie!husc6!seismo!mimsy!chris From: chris@mimsy.UUCP Newsgroups: comp.lang.c Subject: Re: Need help with pointer to array[][] Message-ID: <5347@mimsy.UUCP> Date: Mon, 9-Feb-87 16:28:12 EST Article-I.D.: mimsy.5347 Posted: Mon Feb 9 16:28:12 1987 Date-Received: Wed, 11-Feb-87 04:37:24 EST References: <132@batcomputer.tn.cornell.edu> <1911@utah-gr.UUCP> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 50 Keywords: two-dim arrays In article <1911@utah-gr.UUCP> thomas%spline.uucp@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@mimsy.umd.edu