开发者

Array boundaries and indexes

开发者 https://www.devze.com 2022-12-19 19:03 出处:网络
I had an earlier post link textwhere someone said I had my pointer initialized to the wron开发者_StackOverflow社区g element which I don\'t quite see why, other than they are right and it works with th

I had an earlier post link textwhere someone said I had my pointer initialized to the wron开发者_StackOverflow社区g 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!


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.


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.


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.


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


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


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!


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号