Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you shift the starting index of an array in C?

Tags:

arrays

c

pointers

I am trying to switch the starting index of an array of ints in C. To be precise I have the following array:

{ int array[4] = {1,2,3,4};}

I wish to change {array} to an array of 3 items containing {2,3,4}. I was wondering if there was an easy way to do this using pointers and without shifting all the elements in the array. I am also happy if {array} remains an array of 4 items as long as the first 3 items are {2,3,4}. I tried the following:

{array = &(array[1])}

However, this does not work and I get an error saying {incompatible types when assigning to type ‘int[4]’ from type ‘int *’}.

I was under the impression that a C array was a reference to the first element of the array.

Can anyone help me with this?

like image 740
Dieter Avatar asked Dec 11 '22 10:12

Dieter


1 Answers

You have a few options:

Move all elements left by one

If preservation of the contents are not required:

int array[4] = { 1, 2, 3, 4 };

then you copy/move the elements from index position n to index position n-1:

For example:

int i;
for (i = 1; i < n; ++i)
  array[i-1] = array[i];

You can also look into memmove which might be more efficient.

For example,

memmove(array, array+1, sizeof array - sizeof *array);

which does the same thing as the loop above.

Copy elements into a new array ignoring the first

If preservation of the original data is required, then you can create another array and copy the elements into that ignoring the first element.

For example,

int array1[4] = { 1, 2, 3, 4 };
int array2[3];
int i;

for (i = 0, i < SIZE_OF_SMALLER_ARRAY; ++i)
  array2[i] = array1[i+1]

Use a pointer to refer to array[1] as array[0]

If you want to use pointer eliminating the need to move/copy data:

int array[4] = { 1, 2, 3, 4 };
int *pArray = &array[1];

Now pArray points to the second element in the array effectively allowing you to index array[1] as pArray[0]

Use an array of int pointers

int array[4] = { 1, 2, 3, 4 };
int *parray[3];

int i;
for (i = 0; i < SIZE_OF_SMALLER_ARRAY; ++i)
  parray[i] = &array[i+1];

Caveats

One thing you can't do is...

int array1[4] = { 1, 2, 3, 4 };
array1 = &array1[1]; // !! Compiler Error !!

The reason is array1 is a non-modifiable l-value. Essentially a constant.

You also can not do this...

int array1[4] = { 1, 2, 3, 4 };
int array2[4] = array[1] // !! Compiler error !!

The reason here is you can not initialize an array in this context.

like image 184
ffhaddad Avatar answered Dec 28 '22 00:12

ffhaddad