如何从C中的数组中删除元素? [英] How to remove an element from an array in C?
本文介绍了如何从C中的数组中删除元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
似乎找不到方法....
Can't seem to find a way on how to do it....
例如,如果我有一个数组
for example if I have an array
a = { 1,2,3 }
并且我想删除a [1],所以结果应该是
and I want to delete a[1] so the result would be
a = { 1,3 }
这怎么办?
推荐答案
您可以根据要删除的索引移动所需的元素,如下所示:
You could just shift the desired elements depending on the index to delete like so:
仅将其复制到新数组时,功能更强大,因此在处理一个数组时不再需要忽略最后一个元素.
more robust to just copy over to a new array, then would no longer need to ignore last element when just working with one array.
int a = {1, 2, 3};
int new_a[sizeof(a)/sizeof(a[0]) - 1]; // new array will hold one less value
int pos = 3; // delete the item at the third index
for (i = pos - 1; i < sizeof(a)/sizeof(a[0]) - 1; i++) {
new_a[i] = a[i+1];
}
这篇关于如何从C中的数组中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文