Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!necntc!ima!cfisun!lakart!dg From: dg@lakart.UUCP (David Goodenough) Newsgroups: comp.unix.wizards Subject: Re: Implementation of alloca() and friends Message-ID: <155@lakart.UUCP> Date: 10 Jun 88 16:26:34 GMT References: <16072@brl-adm.ARPA> Organization: Lake - The systems people Lines: 40 From article <16072@brl-adm.ARPA>, by enag@ifi.uio.no: > This discussion on alloca at least gave me something to chew on. > I'm concerned with the implementation of a declaration like this, and > the associated code: > > kaflunk(n, m) > int n, m; > { > int array[n]; > int matrix[n][m]; > long something; > } > > array is easy: make it a pointer, and allocate memory for it (by this > stack allocation feature, or malloc, or something more ingenious), and > use it transparently. > > matrix is worse: of course, it is still a pointer, and memory is > allocated, but you need to hold the size of all but the first dimension > to make the access algorithm work right. I would suggest the following: int **matrix; int i; matrix = alloca(n * sizeof(int *)); for (i = 0; i < n; i++) matrix[i] = alloca(m * sizeof(int)); Now accessing matrix APPEARS to be normal: matrix[foo][blurf] will work, althought the internals of the code generated will be different. Whatever the case using a memory allocator for a multidimensional array is never too pretty. However, in my humble opinion, I would rather get the messy part out of the way when things are set up, and then have useages look normal. -- dg@lakart.UUCP - David Goodenough +---+ | +-+-+ ....... !harvard!cca!lakart!dg +-+-+ | +---+