Memory allocation / data access

Harry Protoolis - Sun EHQ harry at matilda.uk.sun.com
Sat Mar 16 03:47:33 AEST 1991


Jim,

You might be better of using pointers instead of constantly dereferencing array
elements.

cartesian *a_atom, b_atom;

for (a_atom = monomer[i].atom, k = 0; k < natoms; k++, a_atom++) {
    for (b_atom = monomer[j].atom, l = 0; l < natoms; l++, b_atom++) {
        xdis = a_atom->x - b_atom->x;
        ydis = a_atom->y - b_atom->y;
        zdis = a_atom->z - b_atom->z;
    }
}

Your allocation looks alright to me, though if you're allocating largish arrays
on a smallish system (e.g. > 64K on a PC) you might be better off using a
linked list. Oh, and why do you use malloc the first time and calloc the
next ?, as they are both array allocations you should, strictly speaking, be
using calloc for both.

if ((monomer = (solvent *) calloc (nmol, sizeof (solvent *)))==NULL)

Regards
Harry

|> typedef struct {
|>   double          x;
|>   double          y;
|>   double          z;
|> } cartesian;
|> 
|> typedef struct {
|>   cartesian       *atom;
|> } solvent;
|> 
|> solvent        *monomer;
|> 
|> /* Allocate the necessary storage */
|> 
|> if ((monomer = (solvent *) malloc (nmol * sizeof (solvent *)))==NULL)
|>   exit(1);
|> 
|> for (i = 0; i < nmol; i++) 
|>   if ((monomer[i].atom = (cartesian *) calloc (natoms,sizeof(cartesian)))==NULL)
|>     exit(1);
|> 
|> /* check components */
|> 
|> for (k = 0; k < natoms; k++) {
|>   for (l = 0; l < natoms; l++) {
|>     xdis = fabs (monomer[i].atom[k].x - monomer[j].atom[l].x);
|>     ydis = fabs (monomer[i].atom[k].y - monomer[j].atom[l].y);
|>     zdis = fabs (monomer[i].atom[k].z - monomer[j].atom[l].z);
|>   }
|> }

-- 
(smart Internet mailers) harry.protoolis at uk.sun.com
(smart JANET mailers) harry.protoolis at sun-microsystems.co.uk
(dumb uucp mailers) ...!sun!sunuk!harry.protoolis

'When I give food to the poor they call me a saint.
 When I ask why the poor have no food they call me a communist.'
         - Dom Helder Camara



More information about the Comp.lang.c mailing list