Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!rutgers!lll-lcc!seismo!ut-sally!utah-cs!utah-gr!spline!thomas From: thomas@spline.UUCP Newsgroups: comp.lang.c Subject: Re: Need help with pointer to array[][] Message-ID: <1911@utah-gr.UUCP> Date: Sun, 8-Feb-87 15:16:41 EST Article-I.D.: utah-gr.1911 Posted: Sun Feb 8 15:16:41 1987 Date-Received: Mon, 9-Feb-87 04:38:56 EST References: <132@batcomputer.tn.cornell.edu> Sender: news@utah-gr.UUCP Reply-To: thomas%spline.UUCP@utah-gr.UUCP (Spencer W. Thomas) Organization: Univ of Utah CS Dept Lines: 43 Keywords: two-dim arrays In article <132@batcomputer.tn.cornell.edu> hsgj@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@utah-cs.ARPA)