0

I have a constructor for my class Graph:

template <typename T>
Graph<T>::Graph(T ** input)
{
    graphData = input;
}

When I tried to crate a new instance of this class using a two dimensional array instead of int**

int intArray[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
Graph<int>* IntGraph = new Graph<int>(intArray);

I've got an error cannot convert parameter 1 from 'int [3][3]' to 'int **

I'm new to c++ and I thought that these types are compatible. Can you please describe me the difference?

EDIT: since this question was marked as a duplicate, I also wanted to ask, what is the best way to convert one of these types into another, or what to use instead without any loss of performance

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
T.Brown
  • 89
  • 9
  • 5
    See http://stackoverflow.com/questions/14183546/why-does-int-decay-into-int-but-not-int – Michael Mar 01 '16 at 21:23
  • Thank you, now I understand the difference. However, I didn't found the way, how to transform one into another. – T.Brown Mar 01 '16 at 21:28
  • What you're trying to do here looks dangerous and complicated. I can see undefined behaviour coming from someone passing a pointer to a local object into the constructor. Do yourself a favour and use a `std::vector` inside `Graph`. – Christian Hackl Mar 01 '16 at 21:31
  • A held question is a particularly bad place to append a second question. You probably want to make a new question. – user4581301 Mar 01 '16 at 21:41
  • I would love to, but the system dosn't allow me to ask another question for another 3 days. I'm trying my best to ask the questions the right way, but as I can see, this server is not beginner friendly. – T.Brown Mar 01 '16 at 21:44
  • If you have a question, please make a new post, don't edit it into this question. The restriction for 3 days is there for a reason, please don't try to go around it. – Rob Mar 01 '16 at 22:38

2 Answers2

2

int [3][3] is converted in expressions with rare exceptions (for example when used in the sizeof operator) to int ( * )[3].

int ( * )[3] is pointer to an array of type int[3] While int ** is pointer to an object of type int *

Consider the following example

int a[3][3];
int ( *pa )[3] = a;

int * b[3];
int **pb = b;

Or the last declaration you can write like

int * ( *pb ) = b;

In this example pointer pa is initialized with the address of the first element of two-dimensional array a. Elements of a two-dimensional array are one-dimensional arrays.

Pointer pb is also initialized by the address of the first element in this case of array b. Elements of the array are objects of type int *.

You can not convert one of these types into another.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You cannot convert int[][] to int** because int[][] is a continuous block of memory in your case of size 2*3, while int** expects a pointer to a pointer to an int.

AFIK. you can do:

void myfunc(int myarray[][3]);
Jarra McIntyre
  • 1,265
  • 8
  • 13