nonion
nonion

Reputation: 832

Removing first X elements from array

I have an array named arr of size 1024. So basically I want to delete the 1st X elements of the array. How would I do that? This is what I am thinking: Make a pointer pointing to the 1st value of the array (arr[0]). Do pointer arithmetic to take it to the X'th element of the array. Then set the arr[0] to the pointer p, which will effectively remove the first X elements? Will this work? Or is there an easier way to remove the first X elements of the array?

Upvotes: 6

Views: 23664

Answers (6)

kol
kol

Reputation: 28688

Since the array is global it will exist in memory until your program terminates. But this won't stop you declaring a pointer which points to one of its internal items, and using this pointer as the start of your array. With your notations: char* p = arr + X; This way p[0] will be equal to arr[X], p[1] to arr[X + 1], and so on.

Upvotes: 4

Sam
Sam

Reputation: 42357

Based on your requirement to not use memmove and to cause arr[0] to return the result of arr[x], you could do something like this:

char arr[1024];
int arr_size = sizeof(arr) / sizeof(*arr);
char* source;
char* destination;
char* arr_end = arr + arr_size;

//Initialise the array contents

for (destination = arr, source = arr + x; source < arr_end; ++source, ++destination)
    *destination = *source;

Keep in mind that this is just shifting the contents of the array backwards by X. The size of the array is still 1024.

Note that this will not do anything with the remaining X elements at the end of the array. If you want to zero them, you could subsequently do something like this:

for (; destination < arr_end; ++destination)
    *destination = 0;

Upvotes: 0

jxh
jxh

Reputation: 70392

You can treat arr as a circular buffer. However, you cannot access it like a regular array anymore. You would need an interface.

char arr[1024];
int pos = 0;
int size = 0;

#define arr(i) arr[(pos+(i))%1024]

void append (char v) {
    arr(size++) = v;
}

void remove_first_x (int x) {
    pos = (pos + x) % 1024;
    size -= x;
}

Upvotes: 2

jh314
jh314

Reputation: 27802

You can move the pointer X units and treat that as the start of the array:

int arr[1024]; // could be other type as well

...

int *p = arr;
...

p += X; // x is the number of units you want to move

Upvotes: 1

necromancer
necromancer

Reputation: 24641

If arr is declared as char arr[1024]; then you cannot.

If arr is declared as char * arr = (char *)malloc(1024 * sizeof(char)); then: arr += 3

Or declare it as char do_not_use_this_name[1024]; then use char * arr = do_not_use_this_name + 3;

Upvotes: 2

levis501
levis501

Reputation: 4207

check out the function memmove, if you can. This is a great way to move a chunk of memory quickly.

Upvotes: 3

Related Questions