Computational Physics - Department of Physics

(Axel Boer) #1

6.3 Programming Details 161


cout << Content of vector vec in subfunction:''<< endl; for(k = 0; k < col; k++){ cout << vec[k] << endl; } // Then write out the matrix cout << Content of matrix matr in subfunction:''<< endl;
for(m = 0; m < row; m++){
for(k = 0; k < col ; k++){
cout << matr[m][k] << endl;
}
}
}// end of function subfunction


Inline awe declare a pointer to an integer which later will be used to store an address to the
first element of a vector. Similarily,line bdeclares a pointer-to-a-pointer which will contain
the address to a pointer of row vectors, each with col integers. This will then become a matrix
with dimensionality [col][col]
Inline cwe read in the size of vec[] and matr[][] through the numbers row and col.
Next we reserve memory for the vector inline d. Inline ewe use a user-defined function
to reserve necessary memory for matrix[row][col] and againmatr contains the address to the
reserved memory location.
The remaining part of the function main() are as in the previous case down toline f. Here
we have a call to a user-defined function which releases the reserved memory of the matrix.
In this case this is not done automatically.
Inline gthe same procedure is performed for vec[]. In this case the standard C++ library
has the necessary function.
Next, inline han important difference from the previous case occurs. First, the vector
declaration is the same, but the matr declaration is quite different. The corresponding pa-
rameter in the call to sub_1[] inline gis a double pointer. Consequently, matr inline hmust
be a double pointer.
Except for this difference sub_1() is the same as before. Thenew feature in the program
below is the call to the user-defined functionsmatrixandfree_matrix. These functions are
defined in the library filelib.cpp. The code for the dynamic memory allocation is given below.


http://folk.uio.no/compphys/programs/FYS3150/cpp/cpluspluslibrary/lib.cpp
/
The function



  • void*matrix()
    reserves dynamic memory for a two-dimensional matrix
    using the C++ command new. No initialization of the elements.
    Input data:

  • int row - number of rows

  • int col - number of columns

  • int num_bytes- number of bytes for each

  • element
    *Returns a void*pointer to the reserved memory location.
    /


voidmatrix(introw,intcol,intnum_bytes)
{
int i, num;
char
pointer,ptr;
pointer =new(nothrow)char
[row];
if(!pointer){
cout <<"Exception handling: Memory allocation failed";
cout <<" for "<< row <<"row addresses !"<< endl;

Free download pdf