C语言中如何删除数组中的一个元素
比如一个int类型的数组,要删除最后一个元素,该怎么做
[解决办法]
建立新数组,copy 除最后一个元素的所有元素
[解决办法]
楼上正解。
如果数组是用malloc建立的话,重新建立一个,copy所有元素。然后把指针指向新数组,原来的数组free掉。
[解决办法]
#include <string.h>#include <stdio.h>#include <stdlib.h>int main(){ size_t len = 3; //length of the array int * a = calloc(len, sizeof(int)); for (int i = 0; i < len; i++) { a[i] = i + 1; } int pos = 1; //the pos of the element you want to delete memmove(a + pos, a + pos + 1, len - pos - 1); a = (int*)realloc(a, len - 1); for (int i = 0; i < len - 1; i++) { printf("%d\n", a[i]); }}
[解决办法]
1楼的办法只有删除最后一个元素好用
通用的办法还是重新复制一次 只保留需要的元素就行了
如果有大量的增加和删除操作 还是用链表吧