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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…