Sudo
Sudo

Reputation: 991

2D array C++ operator []

I have a 2D array, when I want to assign a value to a cell, it assigns the same value to the opposite cell.

Here's an example :

g.tab = new MyType*[g.width];
for(int i=0;i<g.height;i++) {
    g.tab[i] = new MyType;
}
const int x = 0;
const int y = 1;    
g.tab[x][y].b = true;

The value at g.tab[0][1] and g.tab[1][0] will be the same.

I don't know why...

Thanks for your help.

Upvotes: 0

Views: 107

Answers (2)

Eutherpy
Eutherpy

Reputation: 4571

I think you meant:

for(int i=0;i<g.width;i++)
g.tab[i] = new MyType[g.height];

By writing g.tab[i] = new MyType; you didn't allocate a 2D array.

And depending on the heigth, the i<g.heigth; condition would either compile but not work correctly, or cause some kind of a memory access violation.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254501

You're allocating width pointers; then allocating a single element for height of them. You presumably want to allocate height elements for each one:

for (size_t i = 0; i < g.width; ++i) {
    g.tab[i] = new MyType[g.height];
}

Upvotes: 3

Related Questions