# C/C++ Tips

Passing 1D array as function argument

Example…

// prototype function declaration
void calc(double *x);

double a[1000];
int main()
{
// call calc
calc(a);
}
void calc(double *x)
{
// do some calculations
}

***************************************************************

Dynamic Memory Allocation for 1D Array

int* a = NULL;     // Pointer to int, initialize to nothing.
int n;                      // Size needed for array
cin >> n;               // Read in the size
a = new int[n];     // Allocate n ints and save ptr in a.
for (int i=0; i a[i] = 0; // Initialize all elements to zero.
}
. . . // Use a as a normal array
delete [] a;            // When done, free memory pointed to by a.
a = NULL;            // Clear a to prevent using invalid memory reference.

Alternate declaration method:

#define DYNAMIC_VECTOR(Q,nrows)\
double* Q = NULL;\
Q = new double[nrows];

******************************************************

Dynamic Memory Allocation for 2D Arrays

#define ZERO(Q,nrows,ncols) \
for(long i=0; i<nrows; i++)\
{ for(long j=0; j<ncols; j++)\
{Q[i][j]=0.;}}

#define DYNAMIC_MATRIX(Q,nrows,ncols) \
double **Q;\
Q =new double* [nrows];\
for(long row=0;row<nrows;row++) {Q[row]=new double[ncols]; }\
ZERO(Q,nrows,ncols)

#define DELETE_MATRIX(aaa,nrows)\
for (long i = 0; i < nrows; i++)\
{delete(aaa[i]);}\
delete(aaa); \

* * *

Initialize array.

Example 100 elements each equal to -1.

using namespace std;
std::fill_n(array, 100, -1);

* * *

Tom Irvine