I have a simple class

class Info {
public:
  long				One[31];	
  long				Two[79];
};

i'm reading values from a couple char arrays, when I write to Two[0], it overwrites One[31].

CurInfo->One[31] = atol(BufferOne);
chatoutf("%d",CurInfo->One[31]);
CurInfo->Two[0] = atol(BufferTwo);
chatoutf("%d",CurInfo->One[31]);

if I feed bufferone a -1, and then buffertwo a 623, I get the following output in my chat window:

-1
623

I have searched and searched, and this is just frankly blowing my mind... I'm assuming One[31] is the 4 bytes immediately before Two[0]... but I dont understand why its putting the "623" into the wrong place in memory... anyone know whats going on?

I would post all the code, but its several thousand lines

I found a work around... i really don't want to use it, I want to find out whats going on, but I changed this class to this:

class Info {
public:
  long				One[31];
  long                          Nothing;	
  long				Two[79];
};

this

CurInfo->One[31] = atol(BufferOne);
chatoutf("%d",CurInfo->One[31]);
CurInfo->Two[0] = atol(BufferTwo);
chatoutf("%d",CurInfo->One[31]);

now it outputs

-1
-1

The reason for this problem is that array indexes in C/C++ start at 0 and end at N-1 (not N). So One[31] is not part of the array "long One[31];" it is actually one long beyond the last element of the array. The last element of the array is actually One[30]. The reason why it is the same as Two[0] is that the array Two starts immediately after the array One.

>>I would post all the code, but its several thousand lines
How could you write several thousands of lines without knowing this basic rule of C/C++?

Edited 6 Years Ago by mike_2000_17: n/a

>>How could you write several thousands of lines without knowing this basic rule of C/C++?
Having an off day?
Maintaining/Modifying someone else's code?

@op
As Mike said, with that declaration, there is no such element known as One[31]. That would be element 32 of the array, but there are only 31 elements in the array. Hence the reason C/C++ code that traverses an array stops short of the array's size if it's properly written:

const int ARRAY_SIZE = 5;
int myArray[ARRAY_SIZE] = {0}; //declare a 5-element array (indexes 0-4)

//traverse the array to update the values
for (int i = 0; i < ARRAY_SIZE; ++i) {
  //notice I did not use i <= ARRAY_SIZE,
  //use of ARRAY_SIZE as an index will cause an error
  myArray[i] = i * 2;
}

Edited 6 Years Ago by Fbody: n/a

foolish error, thanks guys =)
I'm a recent VB convert, i'm used to the array starting at 0, and the provided index being the upper bound... at least thats the way I remember it.

This question has already been answered. Start a new discussion instead.