| HappyCowParty (5) | |||
|
I'm having a problem with a 2d pointer array. Outside of the constructor, the addresses seem to get reset. I don't understand, exactly, what's happening. : ( What's got me so confused is that I've done similar things with pointers before. It's just all of a sudden I'm probably doing something really stupid. This is how the class that uses the array is defined, followed by the two functions where the problem occurs:
| |||
|
|
|||
| shacktar (1116) | |||
It looks like an array-out-of-bounds is happening here. The maximum index into the array _river should be HUSBAND1 - 1. | |||
|
|
|||
| HappyCowParty (5) | |
| That part's fine. Husband1, etc, are part of an enum, so they're the actual numbers. ; ( | |
|
|
|
| shacktar (1116) | |
You've declared _river like this:bool _river[HUSBAND1];This means that _river has size HUSBAND1 (I'm aware it's a constant, you just haven't shown its precise value). This also means that the valid indeces when indexing _river are {0, 1, 2, 3, ..., HUSBAND1 - 1}. Your code indexes _river with the index HUSBAND1 (whatever that is), but that's the size of the array. Hence, it is an array-out-of-bounds which would invoke undefined behaviour in your program. Change your loop to the following (notice the strictly less than '<' sign): for(int pos = BOAT; pos < HUSBAND1; pos++)and see if it fixes your issue. | |
|
Last edited on
|
|
| HappyCowParty (5) | |
|
Fascinating! You're totally right. The arrays come out right, but the last value in the enum is not set to false along within the loop, so I must change it to something like this: { cout << crossing_table << endl; for(int pos = BOAT; pos < HUSBAND1; pos++){ _river[pos] = false; } _river[4] = false; input.close(); } That looks rather ugly to me, however. Is that okay, though? I think I needed to create the array as HUSBAND1 + 1, since HUSBAND is part of an enum. When I cout << HUSBAND1, 4 is returned, as there are 5 objects in the enumeration, even though when I create arrays with ints as the index, that int would just be the size, while I'd index with "-1" in mind. Does it make sense why I'm so confused? | |
|
|
|
| shacktar (1116) | |||||
Yes, it looks that way. A common trick with enums is to have the last value be the number of values, like so:
So then you could declare your array like this: bool _river[NUM_RIVER_OBJECTS];so that index x into the array _river would match up with enum value x.
Yes, we're taught since grade school to count from one then during our first programming class we're taught to count from zero. | |||||
|
Last edited on
|
|||||