### Weird thing with structs and arrays

Hello everyone,

A couple days ago I started programming again, but right now I am already stuck on this weird thing. It's probably not weird, but since I don't know how this works it looks weird to me.

Anyway,

In my program I made a struct:
 ``123456`` ``````struct mogelijkheid{ int matrix[nMax+1][nMax]; mogelijkheid* buur; mogelijkheid* kind; }; ``````

So this struct contains a two dimensional array.

I have also created a copyMatrix function to copy this two dimensional array, and it looks like this:

 ``1234567`` ``````void copyMatrix(int source[nMax+1][nMax], int dest[nMax+1][nMax]){ for(int i = 0; i <= nMax+1; i++){ for(int j = 0; j <= nMax; j++){ dest[i][j] = source[i][j]; } } }``````

Ok so let's say I have a two dimensional array called test[nMax+1][nMax] and it's filled with only zero's.
Now if I type this, it doesn't matter in what function, the program hangs:

 ``1234567`` ``````mogelijkheid *m = new mogelijkheid; mogelijkheid *b; copyMatrix(test, m->matrix); //every thing still seems to go fine b = new mogelijkheid; //program hangs ``````

So for some reason, I can't initialize a struct (by saying '= new mogelijkheid') after calling my copyMatrix function.
If I say `b = new mogelijkheid;` without first calling the copyMatrix function, then everything goes fine.

Could you please tell me, what am I doing wrong?
How and where was test defined?

How and were was nMax defined?

Also the following looks malformed.
 ``12`` `````` for(int i = 0; i <= nMax+1; i++){ for(int j = 0; j <= nMax; j++){``````

Since your arrays are defined with a size of nMax+1 and nMax you are accessing your arrays out of bounds.

Last edited on
You created array of `int matrix[nMax+1][nMax]`
and then you used
 ``12`` `````` for(int i = 0; i <= nMax+1; i++){ for(int j = 0; j <= nMax; j++){``````

If you create int array[10], you have items from array[0] to array[9], not array[10]. So you should use "<" not "<=" in your for's.
 ``123`` ``````int matrix[nMax+1][nMax]; //... for(int i = 0; i <= nMax+1; i++){``````

Access out of bounds here. Fix it.
Last edited on
OMG of course!!!
Damn how could I be so stupid.
Thank you very much guys, you all helped me a lot!
Topic archived. No new replies allowed.