C/C++ Tips

Passing 1D array as function argument


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

double a[1000];
int main()
// call calc
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++)\

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

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

* * *

Initialize array.

Example 100 elements each equal to -1.

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

* * *

Tom Irvine

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s