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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

passing refs for 2D arrays

Status
Not open for further replies.

jxxnorth

Programmer
Feb 19, 2002
12
US
What is the correct way to pass a 2d array by ref to a function. This is what I've tried...

void foo (int** array); // or void foo (int*[] array); ??

int main(){
int array[10][10];

foo(array);
}

void foo(int** array){
array[0][0] = 1;
}


 
you can do it like this:

Code:
#define _MAXSIZE_  10

void foo (int array[][_MAXSIZE_]);

int main()
{
  int array[10][10];
  foo(array);

  return 0;
}

void foo (int array[][_MAXSIZE_])
{
   array[0][0] = 1;
}
 
thank you!

now if I wanted to assign the passed array pointer to a member variable of a class or another variable,how should I declare it?

int m_intArray [][20];
//-or-
int* m_intArray[20];

...

void foo (int array[][_MAXSIZE_])
{
m_intArray = array; //this is giving me troubles w/ the declared type

//and then

m_intArray[0][0] = 1
}

I'm trying to save this pointer so that it doesn't need to be passed in for other member functions. Thanks in advance!
 

try to use this:
Code:
#include<string.h>
#define _MAXSIZE_   20
#define arrcpy( a, b )  memcpy( &a, &b, sizeof(a))//array copy


typedef int Array[_MAXSIZE_];

void foo (int array[][_MAXSIZE_]);

class Someclass
{
public:
	Someclass( int size );
	~Someclass();
	
	Array* m_intArray;
};

Someclass::Someclass( int size )
{
	m_intArray = new Array[size]; 
}

Someclass::~Someclass()
{
    //if(m_intArray)
	//delete [] m_intArray;	 
}

int main()
{
  int array[10][20];
  foo(array);

  return 0;
}

void foo (int array[][_MAXSIZE_])
{
    Someclass t(10);
	
	arrcpy( t.m_intArray, array );

	//and then
	t.m_intArray[0][0] = 1;
}
 
if I understand this correctly, t.m_intArray is still just a copy. My goal is to copy the pointer to the original 2D array so that member functions of several classes can access the same chunk of 2D data - not copies. My fall back is to do the following:

int array[200];

array[y*20 + x] = 1;
//equiv of
//int array[10][20];
//array[y][x]= 1;

because array can be passes easily as int*, but my current code is written for a 2D rather than 1D array.

//foo(array);

//void foo(int* array){}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top