returning a pointer to 2d array

Ok, I'm new to pointers as part of our data structure class. The first assignment requires we make a templated function that allocates a 2d array, fills it with a default value and returns a pointer to the start of the array (array[0][0]).

I'm having trouble returning the pointer, I keep getting invalid conversion errors.
this is my .hpp file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template < typename T >
T** getmatrix(int cols, int rows, T def);

template <typename T>
T** getmatrix(int cols, int rows, T def)
{
  T **grid;
  T **p;
  
  grid = new T* [cols]; //allocates rows
  for(int i=0; i<cols; i++)
  {
    grid[i] = new T[rows]; //allocates columns
  }

  for (int i=0; i<cols; i++) //fills array with def value
  {
    for (int k=0; k<rows; k++)
    {
      grid[i][k] = def;
    }
  }
 p = grid[0][0];
 return p;


i think I have this right to set p to return the pointer, but how do I get it to work in my .cpp file?
Instead of lines 23, 24 just return grid:
return grid;
closed account (D80DSL3A)
Line 23. Try p = grid;, or forget line 23 and return grid;.
Thanks, I knew it had to be something stupid and simple like that I was missing.

Now, if someone could tell me how I would go about putting the returned value into a variable, that would help me a ton.

example
this works
cout<<**(getmatrix(3,4,'c'))<<endl;

outputs c

or cout<<**(getmatrix(3,4,15))<<endl;

outputs 15.

but with the templated function, how can I make it return something into a variable?

example: I run
x = getmatrix(3,4,15);

how would that work if i dont know whether x is going to be a int, char, etc?
The third parameter of getmatrix() specify the type of matrix' elements.
1
2
3
4
5
int** x = getmatrix(3, 4, 15); //or getmatrix(3, 4, int(15));
double** y = getmatrix(3, 4, 15.0);

cout << x[0][0] << endl;
cout << y[1][2];
Topic archived. No new replies allowed.