Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell where I am in an array with pointer arithmetic?

Tags:

c

pointers

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_cell = 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?

like image 576
Federico klez Culloca Avatar asked Dec 22 '22 04:12

Federico klez Culloca


2 Answers

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).

like image 123
Bill Lynch Avatar answered Jan 05 '23 01:01

Bill Lynch


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.

like image 21
sharptooth Avatar answered Jan 05 '23 01:01

sharptooth