Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to increment an array in c

Tags:

arrays

c

pointers

I am trying to increment an int array using a variable as the increment but it throws an error.

int array[MAXSIZE];
int n;

//fill the array with some numbers
//some other code

The situation here is that once I analyze the first "n" numbers i will not need them again and it will be a waste of cycles to iterate the array from the starting so i want to increment the array by "n". NOTE: because of the type of the problem that I'm working on I cannot just save the position in a variable and start from that position later using array[position]; I have to increment the pointer permanently.

array += n;

and Throws this error: incompatible type in assignment.
I don't know in advance what "n" is going to be. I tried to use array += sizeof(int)*n; but it fails as well.

like image 582
Ric Avatar asked Dec 11 '25 04:12

Ric


1 Answers

int array[MAXSIZE]; array is an array and not a pointer. You can not increment an array variable. You can do something like:

int *p = array;
p += whatever;

just make sure that you don't deference p when it is pointing to any element beyond the last element of the array.

The fact that printing out array and p will give you the same output (address) does not make them the same things.

like image 141
babon Avatar answered Dec 12 '25 21:12

babon