如何从c中的数组中删除一系列元素 [英] how to remove a range of elements from an array in c
问题描述
我需要从数组中删除一系列元素,但是我不知道如何做。
我尝试了此for循环,其中start是范围的开始,而end是范围的结束。
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];;
}
推荐答案
从数组中删除一系列元素
to remove a range of elements from an array
在C中,一旦定义了 array ,元素范围是固定的。无法将其删除。 @hyde
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.
使用数组 [1,2,3,4,5,6,7]
,我们想删除 [ 3,4,5]
,然后以 [1,2,6,7,x,x,x]
结尾。这里 x
必须是一些值,也许是0。
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代码对于 n
?
我希望循环迭代计数为 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.
这篇关于如何从c中的数组中删除一系列元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!