Date: Sat, 8 May 2004 09:48:15 +0930 From: Malcolm Kay <malcolm.kay@internode.on.net> To: Henrik W Lund <henrik.w.lund@broadpark.no>, freebsd-questions@freebsd.org Cc: ckorves@hotmail.com Subject: Re: segmentation fault-- is my array too long? Message-ID: <200405080948.15164.malcolm.kay@internode.on.net> In-Reply-To: <409AAA48.50409@broadpark.no> References: <20040506190033.A45C616A5CF@hub.freebsd.org> <409AAA48.50409@broadpark.no>
next in thread | previous in thread | raw e-mail | index | archive | help
On Friday 07 May 2004 06:42, Henrik W Lund wrote: .... > malloc() is your friend! :-) > > --> double *ncost = malloc(sizeof (double) * persons * scens); <-- > > This ought to do the trick. Just remember to make sure that malloc > returns a valid pointer, otherwise you'll have another seg fault. > > I'm pretty sure you can adress the pointer like you do with the array > there (ncost[persons][0], etc...); if not, you can always do > ncost(sizeof(double) * persons + 0), etc... > > /* AMENDMENT!!! */ > In my haste, I totally forgot my pointer dereferencing. The correct way > to reference a pointer as a two dimensional array is, of course, thus: > > *(ncost + (sizeof(double) * persons) + 0)) = 0.00; You've still got it wrong! ncost increments in units of size equal to that which it points so it should be: *(ncost + person*scens + scen) where person is the first index and scen the second. or in the particular instance *(ncost + person*scens + 0) = 0.00; For easier to read code it would be better to use: double (*ncost)[scens] = malloc( persons * sizeof *ncost ); and dereference as: ncost[person][scen] or in particular ncost[person][0] = 0.0; And for the OP it is usual to write constants generated with #define in upper-case. It generally seems to help to make the code easier to follow. In this case: PERSONS instead of persons and SCENS instead of scens This also make the distinction between PERSONS and person more evident while retaining their implied connection. Malcolm
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200405080948.15164.malcolm.kay>