Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing first X elements from array

Tags:

c

pointers

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?

like image 543
nonion Avatar asked Jul 13 '13 01:07

nonion


3 Answers

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.

like image 106
kol Avatar answered Nov 01 '22 07:11

kol


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

like image 3
levis501 Avatar answered Nov 01 '22 06:11

levis501


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;

like image 2
necromancer Avatar answered Nov 01 '22 07:11

necromancer