Crystal
Crystal

Reputation: 29518

Array boundaries and indexes

I had an earlier post link textwhere someone said I had my pointer initialized to the wrong element which I don't quite see why, other than they are right and it works with their correction. So here is the basic problem:

If I declare an array from 0 to 30 with

#define ENDPOINT 15
int record[2 * ENDPOINT + 1];
// and want a pointer to be at the middle of the array, so 0 is at the middle, and
// +15 is at 30, and -15 is at 0
// why is int *ptr = &record[ENDPOINT + 1] wrong?  why is the correct declaration
int *ptr = &record[ENDPOINT];

Because if I put the ptr at &record[ENDPOINT], that means the 15th entry in the record array which is the 14th index, and then adding 15 would be only 29 right? Thanks!

Upvotes: 0

Views: 211

Answers (7)

Michael Howard-MSFT
Michael Howard-MSFT

Reputation: 3290

my reply does not answer you question; rather i want to add a best practice. if you're messing around with array indexes, and you're really not 100% sure if you're getting it right and you are using VC++ 2008 or later, please compile the code with /RTC1 which will do run time checks to make sure you are accessing the array bounds correctly.

basically, if the runtime detects you have wandered beyond the array bounds, you app will terminate with a nice stack trace to the offending code.

it's a life-saver. trust me!

Upvotes: 1

Tyler McHenry
Tyler McHenry

Reputation: 76740

Array indices start at zero, sorecord[ENDPOINT] is the 15th index, which is the 16th record in the array. The set [0, 15] (inclusive) contains 16 numbers.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 754760

No, &record[ENDPOINT] means the 16th entry because &record[0] is the first, &record[1] is the second, and so on.

Upvotes: 1

anthares
anthares

Reputation: 11223

Nope record[30] means exactly 30 records, starting from 0

Upvotes: 0

Anon.
Anon.

Reputation: 60033

Because if I put the ptr at &record[ENDPOINT], that means the 15th entry in the record array which is the 14th index

Nope.

It means the entry at record[15] - in other words, the 15th index.

Upvotes: 2

Joel
Joel

Reputation: 5674

Basically if you want to point to the exact middle you want to have an element to point to -- that's the +1 in the definition.

Here's a picture:

123456789012345 x 543210987654321

Since arrays are 0 based and not 1 based, you have:

012345678901234 x-1 432109876543210

Upvotes: 1

fbrereto
fbrereto

Reputation: 35935

record[ENDPOINT] is the 16th element- the array's indices start at 0, so record[0] is the 1st element, record[1] is the 2nd element... and record[ENDPOINT] (is record[15]) is the 16th element.

You have 2*15+1 or 31 elements in your array. Adding 14 to ENDPOINT (15) yields 29, and record[29] is the 30th element in the array. record[30] would be the final, or 31st, element in the array.

Upvotes: 6

Related Questions