user3287183
user3287183

Reputation: 125

Multidimensional array of struct - Segmentation fault

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.

Upvotes: 1

Views: 112

Answers (2)

Rontogiannis Aristofanis
Rontogiannis Aristofanis

Reputation: 9063

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();

Upvotes: 0

HelloWorld123456789
HelloWorld123456789

Reputation: 5359

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.

Upvotes: 1

Related Questions