0

I am trying to create a two dimensional array of pointers.What is wrong with the declaration below

Node* root[100][100] = new Node*[100][100];
Nagsaver
  • 81
  • 2
  • 11
  • 2
    First, tell us where you got that code from or why you expected it to work? (if you have no source, your question is invalid - you can't just dump random code in the compiler and hope for the best) – Luchian Grigore Jun 22 '13 at 06:45
  • "What is wrong with the declaration below" - Well: "error: array initializer must be an initializer list" - Do you trust `clang` or should I explain why this is wrong? –  Jun 22 '13 at 06:46
  • @LuchianGrigore: sure you can! You'll just end up here asking why it doesn't work :) – ChiefTwoPencils Jun 22 '13 at 06:51
  • 2
    @C.Lang, Or you could read a book and get a lot more out of your time than asking tons of questions that are addressed in the book. – chris Jun 22 '13 at 06:53
  • all you need is: Node *root[100][100]; to declare this. related: http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation – Ray Tayek Jun 22 '13 at 07:00

2 Answers2

0

Realize that the first element is a pointer to a pointer so you should be having root as a pointer to a pointer to a pointer.And then essentially you create 100 pointers for each pointer.

Node*** root=new Node**[100];
for(int i=0;i<100;i++)
  root[i]=new Node*[100];

Now root[40][60] will be of type Node*.

See working example here.

Aravind
  • 3,169
  • 3
  • 23
  • 37
  • Thanks aravind...Now if I have to pass such pointers in a function can I just pass root with appropriate index e.g. root[50][60] – Nagsaver Jun 22 '13 at 06:51
  • aravind..your edited code compiles.....but when I pass root[50][60] as a pointer it returns run time error.. – Nagsaver Jun 22 '13 at 07:19
  • Run time error means you have not allocated the pointer, did you run the above code and then call that function? – Aravind Jun 22 '13 at 07:21
  • Probably you din't assign a value to the pointer, and you are trying to access a null pointer. – Aravind Jun 22 '13 at 07:24
  • Anyway this is a Q & A forum, and for extended Q please ask another question, and when you have reached 20 points, try using the chat.We'll be happy to help you there. – Aravind Jun 22 '13 at 07:44
  • thanks aravind...The thing is if i create only one pointer like Node *root = new Node; and then pass root in the function then there is no problem but when I create an array of pointers and pass the pointers one by one ,then the compilers throws a segmentation fault... – Nagsaver Jun 22 '13 at 07:47
0

I wonder if you need "a pointer [to] a 2 dimensional array".

Node (*root)[100][100] = new Node[1][100][100];

or "a pointer [works as] a 2 dimensional array"

Node (*root)[100] = new Node[100][100];
Sorayuki
  • 256
  • 2
  • 7