Dynamic 2D arrays

this is a piece of the code that I use:
1
2
3
4
5
6
7
8
9
10
11
12
13
template < typename T > T ** New2DArray(int cols, int rows)
{
	T **ret = new T *[rows];
	for (int i = 0; i < rows; i++)
	{
		ret[i] = new T[cols];
	}
	return ret;
}
//some function...
c=New2DArray<char>(40,15);
c[2][5]=0;//<- this is where it says it has Access violation writing location 0xabababab(yes it's 0xabababab-not anything else)
//the rest 


what am I doing wrong?
Last edited on
I think a 2D array is considered by the program to be an array of arrays, so you'll need to declare each dynamic array separately ... ?
well yes, that's why I got the New2DArray() function...
where does the compiler know from, how to access the elements of your array?
isn't it enought to declare a dynamic 2d array like this:
1
2
3
4
5
char** c=new char*[15];
for(int i=0;i<15;i++)
{
c[i]=new char[40];
}


same as the example from first post, but without function, but doing that for lets say 10 variables is kinda lot of coding so I thought of creating a function for that...

the part w/o function works, but the one with it doesn't, however they do the same thing...
Last edited on
and what does it means , c = New2DArray<char>(40,15); what is the type of c? nothing ? should not it be char** , or what else?
Last edited on
yes, sorry, the c variable is char**, just forgot to add that to the first post since it'a class variable...
Tried this in gcc and in an online c++ compiler ( http://codepad.org/SIigrOF7 ). It seems to work fine.
Yes, it compiles fine but when it runs it has the acces error.
The code where the assignment happens looks a little contrived. I suspect there is some code between the allocation and assignment that is causing the problem.
I got nested loops that set the array to 0...
for(int i=0;i<40;i++)
for(int j=0;j<15;j++)
c[i][j]=0;
Topic archived. No new replies allowed.