15
4/18/2011 1 Titus Beu 2011 Titus Beu University “Babes-Bolyai” Department of Theoretical and Computational Physics Cluj-Napoca, Romania 2. Scientific programming techniques in C 2. Scientific programming techniques in C Titus Beu 2011 Bibliography Free Integrated Development Environment for C/C++ Program structure. Functions Pointers and lists of arguments Returning variables via argument lists Dynamic array allocation Library for dynamic allocation of arrays

2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

1

Titus Beu 2011

Titus BeuUniversity “Babes-Bolyai”Department of Theoretical and Computational PhysicsCluj-Napoca, Romania

2. Scientific programming techniques in C2. Scientific programming techniques in C

Titus Beu 2011

Bibliography

Free Integrated Development Environment for C/C++

Program structure. Functions

Pointers and lists of arguments

Returning variables via argument lists

Dynamic array allocation

Library for dynamic allocation of arrays

Page 2: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

2

Titus Beu 2011

Dev C++

Bloodshed Dev-C++ – Integrated Development Environment (IDE) for C/C++ for Windows

Download site: http://www.bloodshed.net/dev/devcpp.html

Installer: devcpp-4.9.9.2_setup.exe

Winbgim

Borland BGI Graphics emulation for Windows

Download site: http://usuarios.multimania.es/charlytospage/dev.htm

Installer: Install Winbgim for Dev C++.exe

Titus Beu 2011

Beu, T. A., Numerical Calculus in C, Third Edition, MicroInformatica Publishing House, Cluj-Napoca, 2004) (in Romanian).

W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The Art of Scientific Computing, Second Edition (Cambridge University Press, Cambridge, 1992).

B.W. Kernighan and D.M. Ritchie, The C Programming Language, Second Edition (Prentice-Hall, Englewood Cliffs, NJ, 1988).

E. Yourdon, Techniques of Program Structure and Design (Prentice-Hall, Englewood Cliffs, NJ, 1975).

http://en.wikipedia.org/wiki/C_(programming_language)

Page 3: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

3

Titus Beu 2011

C program – collection of functions

Function main is compulsory – controls the entire execution of the program

Concepts of building scientific applications:

modularization – decomposition of the code in program units (functions or subroutines), which interact only by way of well-defined interfaces (headers with lists of arguments)

encapsulation – control of the scope of objects – visibility outside the program units they have been defined in

Judicious modularization – increases code readability, simplifies debugging and editing, makes possible reutilization of functions in other programs (construction of function libraries)

Excessive modularization – dysfunctional and inefficient programs

Titus Beu 2011

Factorial implementation using global variables:Global variables f and n can be modified by any function of the programDifficult to control collateral effects – no modular programming

#include <stdio.h>

float f; // global variables

int n;

//===========================================================================void Factorial(void)

{int i;

f = 1.0;

for (i=2; i<=n; i++) f *= i;}

//===========================================================================

void main(){

printf("n = "); scanf("%i",&n);

Factorial();

printf("factorial = %g\n",f);}

#include <stdio.h>

float f; // global variables

int n;

//===========================================================================void Factorial(void)

{int i;

f = 1.0;

for (i=2; i<=n; i++) f *= i;}

//===========================================================================

void main(){

printf("n = "); scanf("%i",&n);

Factorial();

printf("factorial = %g\n",f);}

Page 4: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

4

Titus Beu 2011

Factorial implementation using lists of arguments – optimalFunction Fact receives the value n through the list of arguments and returns the factorial through the name – communicates only via header

#include <stdio.h>

//===========================================================================

float Fact(int n)//---------------------------------------------------------------------------

// Returns the factorial of the integer argument n (float type result)//---------------------------------------------------------------------------

{float f;

int i;

f = 1.0;for (i=2; i<=n; i++) f *= i;

return f;}

//===========================================================================

void main(){

int n;

printf("n = "); scanf("%i",&n);printf("factorial = %g\n",Fact(n));

}

#include <stdio.h>

//===========================================================================

float Fact(int n)//---------------------------------------------------------------------------

// Returns the factorial of the integer argument n (float type result)//---------------------------------------------------------------------------

{float f;

int i;

f = 1.0;for (i=2; i<=n; i++) f *= i;

return f;}

//===========================================================================

void main(){

int n;

printf("n = "); scanf("%i",&n);printf("factorial = %g\n",Fact(n));

}

Titus Beu 2011

//===========================================================================

float Fact(int n)//---------------------------------------------------------------------------

// Returns the factorial of the integer argument n using recursivity//---------------------------------------------------------------------------

{return ((n > 1) ? n * Fact(n-1) : 1.0);

}

//===========================================================================

float Fact(int n)//---------------------------------------------------------------------------

// Returns the factorial of the integer argument n using recursivity//---------------------------------------------------------------------------

{return ((n > 1) ? n * Fact(n-1) : 1.0);

}

Factorial implementation using recursivity

Self-calls cause numerous sets of copies of local variables to be stored in the heap

Slower execution and requires more memory

Explicit exit from recursivity has to be implemented in reversed order of calling levels

Compact but inefficient

Page 5: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

5

Titus Beu 2011

Pointer – special type of variable, which takes as values addresses

Pointers store the addresses of the variables they are pointing to:

The address operator & – returns a pointer to its operand

p = &x

assigns the address of variable x to pointer p (p points to x)

The indirection operator * – returns the value of the memory location (variable) to which the pointer points (*p)

Syntax of pointer declaration:

type *name;

type – type of variables the pointer is to point to (essential for indirection)

Example: int *p; (pointer p points to variables of type int)

p x

&x

&x

Titus Beu 2011

Operations with pointers:

(p++) incrementation – address of next memory location

(p--) decrementation – address of previous memory location

Incrementing the variable to which the pointer points:

++(*p)

Important applications of pointers in scientific programming:

returning (modifying) variables from functions via argument lists

dynamic memory allocation for arrays

Page 6: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

6

Titus Beu 2011

Mechanisms of passing arguments to functions:

Passing by value – the values of the actual arguments are copied to the corresponding formal parameters in the called function

Passing by reference – the addresses of the actual arguments are copied to the corresponding formal parameters in the called function – pointers

Both are actually one-directional, “by value” and operate only upon entry:Calling function → Called function

No inverse mechanism of data transmission upon return

Functions can modify local and global variables, or absolute memory locations

Called functions cannot modify (return) arguments received by value

Called functions can modify (return) arguments received by reference – operate on the memory locations received by their addresses using local pointers as aliases

Upon return from the called functions – calling functions “find” the results of the modifications of the variables whose addresses have been passed

Titus Beu 2011

Example: function Swap should interchange the values of its arguments – does not!Passing arguments by valueActual arguments a and b are copied into formal parameters x and yOnly local copies are interchanged (x and y)

//===========================================================================

void Swap(float x, float y) // does not return anything{

float temp;

temp = x;x = y; // only local copies of input

y = temp; // arguments are interchanged}

//===========================================================================

void main(){

float a, b;

........... Swap(a,b);

........... // a and b maintain same values}

//===========================================================================

void Swap(float x, float y) // does not return anything{

float temp;

temp = x;x = y; // only local copies of input

y = temp; // arguments are interchanged}

//===========================================================================

void main(){

float a, b;

........... Swap(a,b);

........... // a and b maintain same values}

Page 7: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

7

Titus Beu 2011

Passing arguments by reference – passing addresses of variables as argumentsSwap operates on the values of a and b from the main program by indirection of pointers xand y which contain the addresses of a and bMain program “finds” interchanged values of a and b after return from Swap

//===========================================================================

void Swap(float *x, float *y){

float temp;

temp = *x;*x = *y;

*y = temp;}

//===========================================================================

void main(){

float a, b;

........... Swap(&a,&b);

........... }

//===========================================================================

void Swap(float *x, float *y){

float temp;

temp = *x;*x = *y;

*y = temp;}

//===========================================================================

void main(){

float a, b;

........... Swap(&a,&b);

........... }

Titus Beu 2011

C++ coding – “hides” the use of pointers in the passing mechanism by referenceFormal parameters receive the address character &Formal parameters are initialized with the actual arguments when the function is calledSimplified coding

//===========================================================================

void Swap(float &x, float &y){

float temp;

temp = x;x = y;

y = temp;}

//===========================================================================

void main(){

float a, b;

........... Swap(a,b);

........... }

//===========================================================================

void Swap(float &x, float &y){

float temp;

temp = x;x = y;

y = temp;}

//===========================================================================

void main(){

float a, b;

........... Swap(a,b);

........... }

Page 8: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

8

Titus Beu 2011

Array – series of elements of same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier

int a[10]; defines an array of 10 consecutive memory locations a[0], a[1],... ,a[9]

Static arrays are allocated during program compilation – by default zero offset

Array name – pointer to the location of the first element

Operations with array elements may be performed equivalently with pointers –C compilers convert internally

Pointer arithmetic:

a+1 equivalent with address &a[1] *(a+1) equivalent with a[1]

a+i equivalent with address &a[i] *(a+i) equivalent with a[i]

&a[0] a[0]

&a[0]

a[1] a[9]

a

Titus Beu 2011

Arrays of arbitrary offset and length – general philosophy for dynamic allocation:

W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The Art of Scientific Computing (Cambridge University Press, Cambridge, 1992).

Basic building block – function malloc defined in header file stdlib.h

void *malloc((size) n)

returns a pointer to a contiguous uninitialized block of n bytes in the heap, or NULL if the request cannot be satisfied (unavailable block)

size_t – type used by C for dimension (in bytes) of objects in memory

(size_t) n – conversion of n to type size_t

To return a pointer to a block of n components of type float:

(float*) malloc((size) (n*sizeof(float)));

sizeof(type) – length in bytes of internal representation of type type

(float*) – conversion into a pointer to locations of type float

Page 9: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

9

Titus Beu 2011

float *Vector(int n)

{float *p;

p = (float*) malloc((size_t) (n*sizeof(float)));

if (!p) {printf("Vector: eroare de alocare !\n");

exit(1);}

return p;}

float *Vector(int n)

{float *p;

p = (float*) malloc((size_t) (n*sizeof(float)));

if (!p) {printf("Vector: eroare de alocare !\n");

exit(1);}

return p;}

Dynamic allocation of a block of n real locations:

Typical context of usage:

int i, n;

float *a; // array name declared as pointer

n = . . . ;a = Vector(n); // a becomes pointer to the allocated block

for (i=0; i<=n-1; i++) a[i] = . . . ; // a is used as array

int i, n;

float *a; // array name declared as pointer

n = . . . ;a = Vector(n); // a becomes pointer to the allocated block

for (i=0; i<=n-1; i++) a[i] = . . . ; // a is used as array

Titus Beu 2011

//===========================================================================

float *Vector(int imin, int imax)//---------------------------------------------------------------------------

// Allocates memory for a vector with components of type float, with indices// in the range [imin,imax]

//---------------------------------------------------------------------------{

float *p;

p = (float*) malloc((size_t) ((imax-imin+1)*sizeof(float)));if (!p) {

printf("Vector: allocation error !\n");exit(1);

}return p - imin;

}

//===========================================================================

float *Vector(int imin, int imax)//---------------------------------------------------------------------------

// Allocates memory for a vector with components of type float, with indices// in the range [imin,imax]

//---------------------------------------------------------------------------{

float *p;

p = (float*) malloc((size_t) ((imax-imin+1)*sizeof(float)));if (!p) {

printf("Vector: allocation error !\n");exit(1);

}return p - imin;

}

Dynamic allocation of an array of offset imin, with legal indices between imin and imax:

Number of relevant components is imax-imin+1

The statement a=Vector(...) assigns the origin of the allocated block to a[0], not to a[imin] as desired

An address preceding the real block origin by imin locations needs to be returned to “trick” the calling function

Page 10: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

10

Titus Beu 2011

//===========================================================================

void FreeVector(float *p, int imin)//---------------------------------------------------------------------------

// Deallocates the memory allocated by function Vector for a vector with// components of type float and offset imin

//---------------------------------------------------------------------------{

free((void*) (p+imin));}

//===========================================================================

void FreeVector(float *p, int imin)//---------------------------------------------------------------------------

// Deallocates the memory allocated by function Vector for a vector with// components of type float and offset imin

//---------------------------------------------------------------------------{

free((void*) (p+imin));}

The pair function which disposes from the heap the block allocated by function Vector

Typical context of utilization (components a[0],..., a[imin-1] should NOT be used):

int i, imin, imax;

float *a;

imin = . . . ;imax = . . . ;

a = Vector(imin,imax);

for (i=imin; i<=imax; i++) a[i] = . . . ;

FreeVector(a,imin);

int i, imin, imax;

float *a;

imin = . . . ;imax = . . . ;

a = Vector(imin,imax);

for (i=imin; i<=imax; i++) a[i] = . . . ;

FreeVector(a,imin);

Titus Beu 2011

Two dimnesional arrays

Name of a two dimensional array – pointer to an array of line pointers, each pointing to the first array element from the corresponding line

Array declaration: float **a

Addressing the whole array: a

Addressing a single line: a[i]

Addressing a single element: a[i][j]

&a[0]

a

a[0][0] a[0][1] a[0][3]&a[0][0]

a[0]

a[1][0] a[1][1] a[1][3]&a[1][0]

a[1]

a[2][0] a[2][1] a[2][3]&a[2][0]

a[2]

a[0][2]

a[1][2]

a[2][1]

Page 11: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

11

Titus Beu 2011

//===========================================================================

float **Matrix(int imin, int imax, int jmin, int jmax)//---------------------------------------------------------------------------

// Allocates memory for a 2D array of float components, with line and column// indices in the range [imin,imax] x [jmin,jmax]

//---------------------------------------------------------------------------{

int i, ni = imax-imin+1, nj = jmax-jmin+1;float **p;

// allocates a pointer to the line pointersp = (float**) malloc((size_t)(ni*sizeof(float*)));

if (!p) {printf("Matrix: level 1 allocation error !\n");

exit(1);}

p -= imin;// allocates the pointer for the first line

p[imin] = (float*) malloc((size_t)(ni*nj*sizeof(float)));if (!p[imin]) {

printf("Matrix: level 2 allocation error !\n");exit(2);

}p[imin] -= jmin;

/* allocates pointers for the rest of the linesfor (i = imin+1; i <= imax; i++) p[i] = p[i-1] + nj;

return p;}

//===========================================================================

float **Matrix(int imin, int imax, int jmin, int jmax)//---------------------------------------------------------------------------

// Allocates memory for a 2D array of float components, with line and column// indices in the range [imin,imax] x [jmin,jmax]

//---------------------------------------------------------------------------{

int i, ni = imax-imin+1, nj = jmax-jmin+1;float **p;

// allocates a pointer to the line pointersp = (float**) malloc((size_t)(ni*sizeof(float*)));

if (!p) {printf("Matrix: level 1 allocation error !\n");

exit(1);}

p -= imin;// allocates the pointer for the first line

p[imin] = (float*) malloc((size_t)(ni*nj*sizeof(float)));if (!p[imin]) {

printf("Matrix: level 2 allocation error !\n");exit(2);

}p[imin] -= jmin;

/* allocates pointers for the rest of the linesfor (i = imin+1; i <= imax; i++) p[i] = p[i-1] + nj;

return p;}

Titus Beu 2011

//===========================================================================

void FreeMatrix(float **p, int imin, int jmin)//---------------------------------------------------------------------------

// Deallocates the memory allocated by function Matrix for a 2D array with// float components, with line offset imin and column offset jmin

//---------------------------------------------------------------------------{

free((void*) (p[imin]+jmin));free((void*) (p+imin));

}

//===========================================================================

void FreeMatrix(float **p, int imin, int jmin)//---------------------------------------------------------------------------

// Deallocates the memory allocated by function Matrix for a 2D array with// float components, with line offset imin and column offset jmin

//---------------------------------------------------------------------------{

free((void*) (p[imin]+jmin));free((void*) (p+imin));

}

The pair function which disposes the allocated block:

Typical usage context:

int i, imin, imax, j, jmin, jmax;

float **a;

imin = . . . ; imax = . . . ;jmin = . . . ; jmax = . . . ;

a = Matrix(imin,imax,jmin,jmax);

for (i=imin; i<=imax; i++)for (j=jmin; j<=jmax; j++) a[i][j] = . . . ;

FreeMatrix(a,imin,jmin);

int i, imin, imax, j, jmin, jmax;

float **a;

imin = . . . ; imax = . . . ;jmin = . . . ; jmax = . . . ;

a = Matrix(imin,imax,jmin,jmax);

for (i=imin; i<=imax; i++)for (j=jmin; j<=jmax; j++) a[i][j] = . . . ;

FreeMatrix(a,imin,jmin);

Page 12: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

12

Titus Beu 2011

//------------------------------- Memalloc.h --------------------------------

//---------------------------------------------------------------------------// Contains functions for dynamic memory allocation for vectors and matrices

//---------------------------------------------------------------------------// Written TBeu 2010

#ifndef _MEMALLOC_

#define _MEMALLOC_

#include <stdio.h>#include <stdlib.h>

..........

#endif

//------------------------------- Memalloc.h --------------------------------

//---------------------------------------------------------------------------// Contains functions for dynamic memory allocation for vectors and matrices

//---------------------------------------------------------------------------// Written TBeu 2010

#ifndef _MEMALLOC_

#define _MEMALLOC_

#include <stdio.h>#include <stdlib.h>

..........

#endif

Titus Beu 2011

//===========================================================================

float *Vector(int imin, int imax)//---------------------------------------------------------------------------

// Allocates memory for a vector with components of type float, with indices// in the range [imin,imax]

//---------------------------------------------------------------------------{

float *p;

p = (float*) malloc((size_t) ((imax-imin+1)*sizeof(float)));if (!p) {

printf("Vector: allocation error !\n");exit(1);

}return p - imin;

}

//===========================================================================void FreeVector(float *p, int imin)

//---------------------------------------------------------------------------// Deallocates the memory allocated by function Vector for a vector with

// components of type float and offset imin//---------------------------------------------------------------------------

{free((void*) (p+imin));

}

//===========================================================================

float *Vector(int imin, int imax)//---------------------------------------------------------------------------

// Allocates memory for a vector with components of type float, with indices// in the range [imin,imax]

//---------------------------------------------------------------------------{

float *p;

p = (float*) malloc((size_t) ((imax-imin+1)*sizeof(float)));if (!p) {

printf("Vector: allocation error !\n");exit(1);

}return p - imin;

}

//===========================================================================void FreeVector(float *p, int imin)

//---------------------------------------------------------------------------// Deallocates the memory allocated by function Vector for a vector with

// components of type float and offset imin//---------------------------------------------------------------------------

{free((void*) (p+imin));

}

Page 13: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

13

Titus Beu 2011

//===========================================================================

int *IVector(int imin, int imax)//---------------------------------------------------------------------------

// Allocates memory for a vector with components of type int, with indices// in the range [imin,imax]

//---------------------------------------------------------------------------{

int *p;

p = (int*) malloc((size_t) ((imax-imin+1)*sizeof(int)));if (!p) {

printf("IVector: allocation error !\n");exit(1);

}return p - imin;

}

//===========================================================================void FreeIVector(int *p, int imin)

//---------------------------------------------------------------------------// Deallocates the memory allocated by function IVector for a vector with

// components of type int and offset imin//---------------------------------------------------------------------------

{free((void*) (p+imin));

}

//===========================================================================

int *IVector(int imin, int imax)//---------------------------------------------------------------------------

// Allocates memory for a vector with components of type int, with indices// in the range [imin,imax]

//---------------------------------------------------------------------------{

int *p;

p = (int*) malloc((size_t) ((imax-imin+1)*sizeof(int)));if (!p) {

printf("IVector: allocation error !\n");exit(1);

}return p - imin;

}

//===========================================================================void FreeIVector(int *p, int imin)

//---------------------------------------------------------------------------// Deallocates the memory allocated by function IVector for a vector with

// components of type int and offset imin//---------------------------------------------------------------------------

{free((void*) (p+imin));

}

Titus Beu 2011

//===========================================================================

float **Matrix(int imin, int imax, int jmin, int jmax)//---------------------------------------------------------------------------

// Allocates memory for a 2D array of float components, with line and column// indices in the range [imin,imax] x [jmin,jmax]

//---------------------------------------------------------------------------{

int i, ni = imax-imin+1, nj = jmax-jmin+1;float **p;

// allocates a pointer to the line pointersp = (float**) malloc((size_t)(ni*sizeof(float*)));

if (!p) {printf("Matrix: level 1 allocation error !\n");

exit(1);}

p -= imin;// allocates the pointer for the first line

p[imin] = (float*) malloc((size_t)(ni*nj*sizeof(float)));if (!p[imin]) {

printf("Matrix: level 2 allocation error !\n");exit(2);

}p[imin] -= jmin;

// allocates pointers for the rest of the linesfor (i = imin+1; i <= imax; i++) p[i] = p[i-1] + nj;

return p;}

//===========================================================================

float **Matrix(int imin, int imax, int jmin, int jmax)//---------------------------------------------------------------------------

// Allocates memory for a 2D array of float components, with line and column// indices in the range [imin,imax] x [jmin,jmax]

//---------------------------------------------------------------------------{

int i, ni = imax-imin+1, nj = jmax-jmin+1;float **p;

// allocates a pointer to the line pointersp = (float**) malloc((size_t)(ni*sizeof(float*)));

if (!p) {printf("Matrix: level 1 allocation error !\n");

exit(1);}

p -= imin;// allocates the pointer for the first line

p[imin] = (float*) malloc((size_t)(ni*nj*sizeof(float)));if (!p[imin]) {

printf("Matrix: level 2 allocation error !\n");exit(2);

}p[imin] -= jmin;

// allocates pointers for the rest of the linesfor (i = imin+1; i <= imax; i++) p[i] = p[i-1] + nj;

return p;}

Page 14: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

14

Titus Beu 2011

//===========================================================================

void FreeMatrix(float **p, int imin, int jmin)//---------------------------------------------------------------------------

// Deallocates the memory allocated by function Matrix for a 2D array with// float components, with line offset imin and column offset jmin

//---------------------------------------------------------------------------{

free((void*) (p[imin]+jmin));free((void*) (p+imin));

}

//===========================================================================

void FreeMatrix(float **p, int imin, int jmin)//---------------------------------------------------------------------------

// Deallocates the memory allocated by function Matrix for a 2D array with// float components, with line offset imin and column offset jmin

//---------------------------------------------------------------------------{

free((void*) (p[imin]+jmin));free((void*) (p+imin));

}

Titus Beu 2011

//===========================================================================

int **IMatrix(int imin, int imax, int jmin, int jmax)//---------------------------------------------------------------------------

// Allocates memory for a 2D array of float components, with line and column// indices in the range [imin,imax] x [jmin,jmax]

//---------------------------------------------------------------------------{

int i, ni = imax-imin+1, nj = jmax-jmin+1;int **p;

// allocates a pointer to the line pointersp = (int**) malloc((size_t)(ni*sizeof(int*)));

if (!p) {printf("Matrix: level 1 allocation error !\n");

exit(1);}

p -= imin;// allocates the pointer for the first line

p[imin] = (int*) malloc((size_t)(ni*nj*sizeof(int)));if (!p[imin]) {

printf("Matrix: level 2 allocation error !\n");exit(2);

}p[imin] -= jmin;

// allocates pointers for the rest of the linesfor (i = imin+1; i <= imax; i++) p[i] = p[i-1] + nj;

return p;}

//===========================================================================

int **IMatrix(int imin, int imax, int jmin, int jmax)//---------------------------------------------------------------------------

// Allocates memory for a 2D array of float components, with line and column// indices in the range [imin,imax] x [jmin,jmax]

//---------------------------------------------------------------------------{

int i, ni = imax-imin+1, nj = jmax-jmin+1;int **p;

// allocates a pointer to the line pointersp = (int**) malloc((size_t)(ni*sizeof(int*)));

if (!p) {printf("Matrix: level 1 allocation error !\n");

exit(1);}

p -= imin;// allocates the pointer for the first line

p[imin] = (int*) malloc((size_t)(ni*nj*sizeof(int)));if (!p[imin]) {

printf("Matrix: level 2 allocation error !\n");exit(2);

}p[imin] -= jmin;

// allocates pointers for the rest of the linesfor (i = imin+1; i <= imax; i++) p[i] = p[i-1] + nj;

return p;}

Page 15: 2. Scientific programming techniques in Cphys.ubbcluj.ro/~tbeu/MD/C2.pdf · 2011-04-18 · W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery, Numerical Recipes in C: The

4/18/2011

15

Titus Beu 2011

//===========================================================================

void FreeIMatrix(int **p, int imin, int jmin)//---------------------------------------------------------------------------

// Deallocates the memory allocated by function IMatrix for a 2D array with// int components, with line offset imin and column offset jmin

//---------------------------------------------------------------------------{

free((void*) (p[imin]+jmin));free((void*) (p+imin));

}

//===========================================================================

void FreeIMatrix(int **p, int imin, int jmin)//---------------------------------------------------------------------------

// Deallocates the memory allocated by function IMatrix for a 2D array with// int components, with line offset imin and column offset jmin

//---------------------------------------------------------------------------{

free((void*) (p[imin]+jmin));free((void*) (p+imin));

}