Page 310 - The Combined Finite-Discrete Element Method
P. 310
DYNAMIC MEMORY ALLOCATION 293
DBL **TalDBL2(m2,m1)
INT m2; INT m1;
{ INT isize,i2;
DBL *p1;
DBL **p2;
void *v1;
isize=sizeof(DBL*)*(m2+3)+
sizeof(DBL )*(m2*m1+3);
if(isize==0)return DBL2NULL;
v1=MALLOC(isize);
p2=(DBL**)v1;
p1=(DBL*)v1;
p1=p1+((m2+1)*sizeof(DBL**))/sizeof(DBL)+2;
for(i2=0;i2<m2;i2++)
{ p2[i2]=p1+i2*m1;
}
return p2;
}
Listing 10.3 Dynamic allocation of the two-dimensional array – file frame.c.
most of the combined finite-discrete element in-core database takes the form of arrays.
Fixed size 2D or 3D arrays are very difficult to handle, while access to individual numbers
is expensive. For readers familiar with FORTRAN, it is worth mentioning that the same
happens when multidimensional arrays are used in FORTRAN codes.
Well designed dynamic arrays are usually much faster and allow better flexibility with-
out any change in the syntax. Dynamic allocation of the two dimensional array is shown
in Listing 10.3. The function TalDBL2 calculates the size of the array and allocates space
for it.
This is followed by breaking the array into m2 one-dimensional arrays. Each of these
one-dimensional arrays is of size m1 elements. Each of the m2 one-dimensional arrays is
allocated a pointer. All these pointers are stored as a one-dimensional array of pointers.
A pointer p2 to the first element of this one-dimensional array of pointers is returned.
This pointer is therefore a pointer to a pointer. The advantage of such an array is the way
DBL FunctionUsingDynamicArray(p2)
DBL **p2
{ DBL x;
DBL y;
DBL *p1
p1=*(p2+5);
y=*(p1+7);
/* equivalent syntax */
x=p2[5][7];
return (x-y);
}
Listing 10.4 An example of accessing an element of a two-dimensional dynamic array.