Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!usc!rpi!crdgw1!camelback!volpe From: volpe@camelback.crd.ge.com (Christopher R Volpe) Newsgroups: comp.lang.c Subject: Re: 2d arrays Message-ID: <17581@crdgw1.crd.ge.com> Date: 14 Mar 91 13:36:58 GMT References: <1991Mar13.183807.23254@ux1.cso.uiuc.edu> <1065@nih-csl.nih.gov> Sender: news@crdgw1.crd.ge.com Reply-To: volpe@camelback.crd.ge.com (Christopher R Volpe) Lines: 41 In article <1065@nih-csl.nih.gov>, pfeifer@alw.nih.gov (John Pfeifer) writes: |>In article <1991Mar13.183807.23254@ux1.cso.uiuc.edu>, sasg0244@uxa.cso.uiuc.edu (Steven Arthur Sivier) writes: |>|> |>|> i've always tried to avoid 2d arrays, but because of a library |>|> function i need to call i need to use 2d arrays. the problem |>|> is i have to malloc the 2d array. can i just malloc the array |>|> to a char pointer and then use it as a 2d array? that is, if |>|> the array has dimensions x by y can i use: |>|> char *array; |>|> array = malloc(x * y); |>|> array[0][0] = 'a' |> |>If I understand you correctly, no. |>char[][] is an array of arrays, ie. **char Try: ^^^^^^^^ ^^^^^^This is not the same thing as This is not valid C. an array of arrays. |> char **array; |> array = malloc(x*sizeof(*char)); |> for(i=0;i array[i] = malloc(y*sizeof(char)); |> |>|> also, inasmuch as i need to pass this array to a library function, |>|> can i just send the pointer even though the function expects a |>|> 2d array? |> |>Yes. |>See section A8.6.2 in K&R (2nd ed.) No. The two step malloc method you used will allow you to reference the object as if it were a 2D array, i.e., you can say "array[a][b]" and it will work, but the storage is not laid out like a true 2D array that you would declare with "char array[DIM1][DIM2];". If you pass your "char **array" to a library routine that expects a true 2D array, it will choke big time. ================== Chris Volpe G.E. Corporate R&D volpecr@crd.ge.com