In C, I have declared a memory area like this:
int cells = 512;
int* memory = (int*) malloc ((sizeof (int)) * cells);
And I place myself more or less in the middle
int* current_c开发者_StackOverflowell = memory + ((cells / 2) * sizeof (int));
My question is, while I increment *current_cell
, how do I know if I reached the end of the allocated memory area?
if (current_cell >= memory + cells)
no_longer_in_valid_memory;
However! You have a large problem in your code. If you want current_cell to be somewhere near the middle of the memory region, you should actually do this:
int* current_cell = memory + (cells / 2);
The pointer arithmetic will take care of the multiplying by sizeof(int).
While you're within the valid indices the following holds true:
memory <= current_cell && current_cell < memory + cells
so if you only increment the address it's enough to check for
current_cell < memory + cells
however be careful - you might increment the address by such a bug value that it overflows and becomes less than memory
. Only use the second simpilfied condition if you're sure overflow can't happen.
And I place myself more or less in the middle
int* current_cell = memory + ((cells / 2) * sizeof (int));
Actually, no. The correct expression would be:
int* middle = memory + cells / 2;
since pointer arithmetic takes the type of the pointer into account. In other words, this expression:
memory + 1
increments the pointer not by a single byte but by sizeof(int)
bytes.
The index in the array, which starts at memory
, equivalent to the pointer current
, is just current - memory
-- the "scaling" (by sizeof(int)
) is taken care of for you. So, you know the pointer is valid (i.e., within the bounds of the cells
-long array starting at memory
) if and only if the index is >=0
and <cells
(from 0 to 511 included, in your example):
((current - memory) >= 0) && ((current - memory) < cells)
精彩评论