1

I have a pointer to array of structure and when I try to initialize it, I get a segmentation fault.

MyStruct **** node = NULL;
node[0][0][0] = new MyStruct();

I tried to use 2D array and it Works fine.

What is wrong?

Thanks for your replies.

2
  • 3
    c2.com/cgi/wiki?ThreeStarProgrammer Commented Mar 29, 2014 at 15:45
  • Isn't vector slower? Ok, now I rewrited it to vector <vector <vector <MyStruct* > > > node; and still segfault Commented Mar 29, 2014 at 16:18

2 Answers 2

1

You need to allocate memory before using it. You can't just jump 3 levels without allocating and use it.

Allocate node first. Then you can access node[0].

Now if you allocate node[0], you can access node[0][0].

Go on like this.

Sign up to request clarification or add additional context in comments.

3 Comments

But in general, prefer using std::vector
@lethal-guitar Yeah sure. Just answering to the question.
Yeah, that was meant mainly for the OP :)
0

Try to dynamically allocate the array first, using the new operator:

MyStruct ****node = new MyStruct***[MAX_SIZE];
for(int i=0; i<MAX_SIZE; ++i) node[i] = new MyStruct**[MAX_SIZE];
for(int i=0; i<MAX_SIZE; ++i) 
  for(int j=0; j<MAX_SIZE; ++j) node[i][j] = new MyStruct*[MAX_SIZE];
node[0][0][0] = new MyStruct();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.