Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pass 2-D Array to Subroutine

Status
Not open for further replies.

OceanDesigner

Programmer
Oct 30, 2003
173
US
I think this should be simple, but I cannot figure it out. I have defined a 2-D array in my main routine as follows:

double X[9][2];

I am trying to pass its pointer to a subroutine so that I can directly modify the variable within the subroutine. The call to the routine is:

var = Fn(&X);

The function prototype is:

Fn(double *A);

No matter what combination of * and & I use, I get an error that the dimensions are not specified correctly in the subroutine Fn. I would really appreciate any help I can get on this.

Jeff
 
double Fn(double[][2]);//Function prototype
int main()
{
double d[9][2];
var = Fn(d);
return 0;
}
double Fn(double d[][2])
{
//Do your stuff here
}

Hope this helps
Rgds
Koti
 
I put here 2 examples:
1. You have to declare explicit the dimensions
Code:
void Fn(double a[3][4])
{
	double sum = 0;
	for (int i=0;i<3;i++)
	{
	for (int j=0;j<4;j++)
           sum+=a[i][j];
	}
}
//2D-array (dim1 * dim2) reduced to one dimension
//This function take a pointer to a 2D array (dim1 * dim2) of doubles and initializes it with a value and calculates the sum of elements  

void Fn(double *a, int dim1, int dim2)
{
	double sum = 0;
	int k=0;
	for (int i=0;i<dim1;i++)
	{
		for (int j=0;j<dim2;j++)
           *(a + dim2*i + j) = k++;
	}
	for (i=0;i<dim1;i++)
	{
		for (int j=0;j<dim2;j++)
           sum+=*(a + dim2*i + j);
	}
   
}

void main (void)
{
double a[3][4]={{0,0,0,0},{0,0,0,0},{0,0,0,0}};
double X[9][2];
Fn(a);
Fn(&X[0][0],9,2);
}
// The 2nd example allows you to pass a dynamic allocated array instead the previous where you have to know the size.
Example:
double *m_dArray = malloc(sizeof(double)*dim1*dim2);
Fn(m_dArray,dim1,dim2);
To access the [i][j] element use 
*(m_dArray + dim2 * i + j) where i in {0,..dim1-1), j in (0,...dim2-1);

-obislavu-

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top