Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to remove a range of elements from an array but I can't figure out how. I tried this for loop where start is that start of the range and end is the end of the range.

for (i=0;i<n;i++){
a1[start+i] = a1[end+i+1];;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
171 views
Welcome To Ask or Share your Answers For Others

1 Answer

to remove a range of elements from an array

In C, once an array is defined, the range of elements is fixed. They cannot be removed. @hyde


Code can at run time, re-assign element values.

With an array [1,2,3,4,5,6,7] and we want to "removed" [3,4,5] and then end up with [1,2,6,7, x, x, x]. Here x needs to be some value, perhaps 0.

size_t start;                              // Array index of sub-range beginning to "remove"
size_t end;                                // Array index of sub-range end to "remove"
size_t n = sizeof a1/sizeof a1[0];           // Number of elements in the array
assert(start < n && end < n && start <= end);// Make certain we have sane input    

size_t n_move = end - start + 1; // Number of elements to move 
memmove(&a1[start], &a1[end + 1], sizeof a1[0]*n_move);

size_t n_clear = n - end; // Number of elements to zero 
memset(&a1[end + 1], 0, sizeof a1[0]*n_clear);

OP code is questionable as to what is n?
I'd expect the loop iteration count to be end - start + 1.

sub_range_count = end - start + 1;
for (i=0; i<sub_range_count; i++){
  a1[start+i] = a1[end+i+1];;
}

This still leaves the later part of the array with the original values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...