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!

Why can't you pass 2d pointers as const?

Status
Not open for further replies.

neseidus

Programmer
Sep 1, 2004
41
CA
I don't understand why the following doesn't compile:

Code:
#include <iostream>
using namespace std;

/**
 *	Utility function used to allocate 2-D arrays
 */
template <typename T>
T** new2DArray( const int& d1, const int& d2 )
{
	T ** result = new T*[d1];
	result[0] = new T[d1 * d2];

	for (int row=1; row < d1; row++)
	{
		result[row] = result[row-1] + d2;
	}

	return result;
}

void t1( const int* test )
{
     // Can't modify array
}

void t2( const int** test )
{
     // Can't modify 2D array
}

void main()
{
	int* test1 = new int();
	int** test2 = new2DArray<int> (3, 3);

	t1( test1 );	// Compiles
	t2( test2 );	// Doesn't compile

	delete test1;

	delete test2[0];
	delete test2;
}
 
It's a correct compiler behaviour. No legal conversion
Code:
T** => const T** (and vice versa)
in C++.
There are two legal conversions:
Code:
T  => const T
T* => const T*
Conversion "T** --> const T**" cannot be derived from those two rules (MSDN, article Q87020, for example).

Don't uncheck Process TGML flag in the form...

You can force a conversion by brutal force method cast...
 
You can encapsulate the arrays to solve the problem.

Code:
#include <vector>

typedef std::vector< std::vector <int> > My2DArray;

...
void someFunc(const My2DArray& arr)
{
  ...
}


/Per
[sub]
&quot;It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure.&quot;[/sub]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top